repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
marketplacer/Dodo
Dodo/Utils/DodoColor.swift
2
1790
import UIKit /** Creates a UIColor object from a string. Examples: DodoColor.fromHexString('#340f9a') // With alpha channel DodoColor.fromHexString('#f1a2b3a6') */ public class DodoColor { /** Creates a UIColor object from a string. - parameter rgba: a RGB/RGBA string representation of color. It can include optional alpha value. Example: "#cca213" or "#cca21312" (with alpha value). - returns: UIColor object. */ public class func fromHexString(_ rgba: String) -> UIColor { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 if !rgba.hasPrefix("#") { print("Warning: DodoColor.fromHexString, # character missing") return UIColor() } let index = rgba.index(rgba.startIndex, offsetBy: 1) let hex = String(rgba.suffix(from: index)) let scanner = Scanner(string: hex) var hexValue: CUnsignedLongLong = 0 if !scanner.scanHexInt64(&hexValue) { print("Warning: DodoColor.fromHexString, error scanning hex value") return UIColor() } if hex.count == 6 { red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 } else if hex.count == 8 { red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 } else { print("Warning: DodoColor.fromHexString, invalid rgb string, length should be 7 or 9") return UIColor() } return UIColor(red: red, green: green, blue: blue, alpha: alpha) } }
mit
e6dcd4ec40047a5ed59209bedb188aaa
27.870968
153
0.622905
3.736952
false
false
false
false
danpratt/Simply-Zen
Simply Zen/View Controllers/MoodZenViewController.swift
1
5459
// // MoodZenViewController.swift // Simply Zen // // Created by Daniel Pratt on 5/19/17. // Copyright © 2017 Daniel Pratt. All rights reserved. // import UIKit import AVFoundation // Mark: - MoodZenViewController Class class MoodZenViewController: UIViewController, MoodZenViewDelegate { // MARK: - Properties @IBOutlet weak var moodZenView: MoodZenView! var moodCourse: SZCourse! // Delegate let delegate = UIApplication.shared.delegate as! AppDelegate // For sound var soundEffectPlayer: SoundEffect! // For haptics var areHapticsEnabled: Bool! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Hide nav bar navigationController?.navigationBar.isHidden = true // Load sound effect Engine soundEffectPlayer = SoundEffect() // Setup animations and enable button taps moodZenView.addFloatAnimation() moodZenView.moodZenViewDelegate = self // Load haptic settings if let hapticsEnabled = UserDefaults.standard.value(forKey: "areUiHapticsOn") as? Bool { areHapticsEnabled = hapticsEnabled } else { areHapticsEnabled = true UserDefaults.standard.set(areHapticsEnabled, forKey: "areUiHapticsOn") } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) moodZenView.removeAllAnimations() } // MARK: - MoodZenViewDelegate Methods func sadPressed(sad: UIButton) { if areHapticsEnabled { let notification = UINotificationFeedbackGenerator() notification.notificationOccurred(.success) } soundEffectPlayer.playSoundEffect() moodZenView.addSadTappedAnimation { (finished) in if finished { self.moodCourse = SZCourse.sadCourse() self.pushMeditationView() } } } func happyPressed(happy: UIButton) { if areHapticsEnabled { let notification = UINotificationFeedbackGenerator() notification.notificationOccurred(.success) } soundEffectPlayer.playSoundEffect() moodZenView.addHappyTappedAnimation { (finished) in if finished { self.moodCourse = SZCourse.happyCourse() self.pushMeditationView() } } } func cantSleepPressed(cantSleep: UIButton) { if areHapticsEnabled { let notification = UINotificationFeedbackGenerator() notification.notificationOccurred(.success) } soundEffectPlayer.playSoundEffect() moodZenView.addCantSleepTappedAnimation { (finished) in if finished { self.moodCourse = SZCourse.cantSleepCourse() self.pushMeditationView() } } } func upsetPressed(upset: UIButton) { if areHapticsEnabled { let notification = UINotificationFeedbackGenerator() notification.notificationOccurred(.success) } soundEffectPlayer.playSoundEffect() moodZenView.addUpsetTappedAnimation { (finished) in if finished { self.moodCourse = SZCourse.upsetCourse() self.pushMeditationView() } } } // MARK: - Push Meditation View private func pushMeditationView() { // Create variables for VC and course / lesson to load let meditationVC = self.storyboard?.instantiateViewController(withIdentifier: "meditationView") as! MeditationViewController let selectedCourse = moodCourse.name var coredDataCourse: Course! let maxlevel = moodCourse.lessons.count var level: Int = Int(arc4random_uniform(UInt32(maxlevel))) var addedCourse = false // Check to see if the user already has a history if let courses = self.delegate.user.courses?.array as? [Course] { for course in courses { if course.courseName == selectedCourse { addedCourse = true coredDataCourse = course break } } } // If the course hasn't been added yet create it and add to the user if !addedCourse { // create course Core Data object and add it to user coredDataCourse = Course(courseName: selectedCourse!, user: delegate.user, insertInto: delegate.stack.context) delegate.user.addToCourses(coredDataCourse) delegate.stack.save() } // Load lesson and attach to meditationVC // Make sure that level index is not out of range of the array // Make sure that level is not out of array index if !(level < maxlevel) { level = 0 } else if level > maxlevel - 1 { level = maxlevel - 1 } meditationVC.lesson = moodCourse.lessons[level] meditationVC.lessonFileName = meditationVC.lesson.lessonFileName meditationVC.coreDataCourse = coredDataCourse self.navigationController?.pushViewController(meditationVC, animated: true) } }
apache-2.0
0cf2a1d6d18a49696332b32097e339b5
31.682635
132
0.609381
5.496475
false
false
false
false
DRybochkin/Spika.swift
Spika/ViewController/CSBaseViewController.swift
1
2083
// // BaseViewController.h // Prototype // // Created by Dmitry Rybochkin on 25.02.17. // Copyright (c) 2015 Clover Studio. All rights reserved. // import UIKit //import AFNetworking class CSBaseViewController: UIViewController { var loadingIndicator: UIActivityIndicatorView! var indicatorBackground: UIView! var sizeOfView = CGRect.zero var activeUser: CSUserModel! func setSelfViewSizeFrom(_ frame: CGRect) { sizeOfView = frame } func showIndicator() { if (loadingIndicator == nil) { indicatorBackground = UIView() indicatorBackground.frame = sizeOfView indicatorBackground.backgroundColor = kAppBlackColor(0.4) view.addSubview(indicatorBackground) indicatorBackground.bringSubview(toFront: view) loadingIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) loadingIndicator.frame = CGRect(x: CGFloat(0.0), y: CGFloat(0.0), width: CGFloat(40.0), height: CGFloat(40.0)) loadingIndicator.center = indicatorBackground.center indicatorBackground.addSubview(loadingIndicator) loadingIndicator.bringSubview(toFront: indicatorBackground) UIApplication.shared.isNetworkActivityIndicatorVisible = true } loadingIndicator.isHidden = false loadingIndicator.startAnimating() loadingIndicator.tag = 1 } func hideIndicator() { if (loadingIndicator != nil) { loadingIndicator.tag = 0 loadingIndicator.stopAnimating() UIApplication.shared.isNetworkActivityIndicatorVisible = false indicatorBackground.isHidden = true } } override func viewDidLoad() { super.viewDidLoad() setSelfViewSizeFrom(UIScreen.main.bounds) // Do any additional setup after loading the view. edgesForExtendedLayout = [] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
3bb8fd0ee526580a896dd8164ef33a45
32.596774
122
0.671627
5.58445
false
false
false
false
jack-cox-captech/HomeKitBrowser
HomeKitBrowser/HKBHomeConfigTableViewController.swift
1
4954
// // HKBHomeConfigTableViewController.swift // HomeKitBrowser // // Created by Jack Cox on 1/25/15. // Copyright (c) 2015 CapTech Consulting. All rights reserved. // import UIKit import HomeKit let homeCell = "homeCell" let addHomeSegue = "addHome" class HKBHomeConfigTableViewController: UITableViewController, HMHomeManagerDelegate { var homeManager:HMHomeManager = HMHomeManager() override func viewDidLoad() { super.viewDidLoad() var addItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "addHomePressed:") self.navigationItem.rightBarButtonItem = addItem // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() homeManager.delegate = self; } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // make myself the delegate again self.homeManager.delegate = self } func addHomePressed(sender: AnyObject!) { println("Add home button pressed") self.performSegueWithIdentifier(addHomeSegue, sender: sender) } // MARK: HMHomeManagerDelegate func homeManagerDidUpdateHomes(manager: HMHomeManager!) { println("homes = \(homeManager.homes)") self.tableView.reloadData() } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. if (segue.identifier == "showRoom") { let ctl = segue.destinationViewController as HKBRoomConfigTableViewController let cell = sender as HKBHomeTableViewCell ctl.home = cell.home } else if (segue.identifier == addHomeSegue) { let ctl = segue.destinationViewController as HKBAddHomeViewController ctl.homeManager = self.homeManager } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return homeManager.homes.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(homeCell, forIndexPath: indexPath) as HKBHomeTableViewCell let home = homeManager.homes[indexPath.row] as HMHome cell.home = home cell.textLabel?.text = home.name if (home.primary) { cell.imageView?.contentMode = UIViewContentMode.ScaleToFill cell.imageView?.image = UIImage(named: "1040-checkmark-selected") } else { cell.imageView?.image = nil; } return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ }
mit
c6dd56dce8fc2dafefc2ef404f13dc8a
33.402778
157
0.67178
5.455947
false
false
false
false
LoopKit/LoopKit
LoopKitUI/ChartColorPalette.swift
1
714
// // ChartColorPalette.swift // LoopKitUI // // Created by Bharat Mediratta on 3/29/17. // Copyright © 2017 LoopKit Authors. All rights reserved. // import UIKit /// A palette of colors for displaying charts public struct ChartColorPalette { public let axisLine: UIColor public let axisLabel: UIColor public let grid: UIColor public let glucoseTint: UIColor public let insulinTint: UIColor public init(axisLine: UIColor, axisLabel: UIColor, grid: UIColor, glucoseTint: UIColor, insulinTint: UIColor) { self.axisLine = axisLine self.axisLabel = axisLabel self.grid = grid self.glucoseTint = glucoseTint self.insulinTint = insulinTint } }
mit
076c9c8096260ea5628dabdc3d3aeb34
26.423077
115
0.698457
4.295181
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Models/BusinessResult/PXBusinessResultViewModel+Tracking.swift
1
8423
import Foundation // MARK: Tracking extension PXBusinessResultViewModel { func getFooterPrimaryActionTrackingPath() -> String { let paymentStatus = businessResult.paymentStatus var screenPath = "" if paymentStatus == PXPaymentStatus.APPROVED.rawValue || paymentStatus == PXPaymentStatus.PENDING.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getSuccessPrimaryActionPath() } else if paymentStatus == PXPaymentStatus.IN_PROCESS.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getFurtherActionPrimaryActionPath() } else if paymentStatus == PXPaymentStatus.REJECTED.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getErrorPrimaryActionPath() } return screenPath } func getFooterSecondaryActionTrackingPath() -> String { let paymentStatus = businessResult.paymentStatus var screenPath = "" if paymentStatus == PXPaymentStatus.APPROVED.rawValue || paymentStatus == PXPaymentStatus.PENDING.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getSuccessSecondaryActionPath() } else if paymentStatus == PXPaymentStatus.IN_PROCESS.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getFurtherActionSecondaryActionPath() } else if paymentStatus == PXPaymentStatus.REJECTED.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getErrorSecondaryActionPath() } return screenPath } func getHeaderCloseButtonTrackingPath() -> String { let paymentStatus = businessResult.paymentStatus var screenPath = "" if paymentStatus == PXPaymentStatus.APPROVED.rawValue || paymentStatus == PXPaymentStatus.PENDING.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getSuccessAbortPath() } else if paymentStatus == PXPaymentStatus.IN_PROCESS.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getFurtherActionAbortPath() } else if paymentStatus == PXPaymentStatus.REJECTED.rawValue { screenPath = TrackingPaths.Screens.PaymentResult.getErrorAbortPath() } return screenPath } } // MARK: PXCongratsTrackingDataProtocol Implementation extension PXBusinessResultViewModel: PXCongratsTrackingDataProtocol { func hasBottomView() -> Bool { return businessResult.getBottomCustomView() != nil } func hasTopView() -> Bool { return businessResult.getTopCustomView() != nil } func hasImportantView() -> Bool { return businessResult.getImportantCustomView() != nil } func hasExpenseSplitView() -> Bool { return pointsAndDiscounts?.expenseSplit != nil && MLBusinessAppDataService().isMp() ? true : false } func getScoreLevel() -> Int? { return PXNewResultUtil.getDataForPointsView(points: pointsAndDiscounts?.points)?.getRingNumber() } func getDiscountsCount() -> Int { guard let numberOfDiscounts = PXNewResultUtil.getDataForDiscountsView(discounts: pointsAndDiscounts?.discounts)?.getItems().count else { return 0 } return numberOfDiscounts } func getCampaignsIds() -> String? { guard let discounts = PXNewResultUtil.getDataForDiscountsView(discounts: pointsAndDiscounts?.discounts) else { return nil } var campaignsIdsArray: [String] = [] for item in discounts.getItems() { if let id = item.trackIdForItem() { campaignsIdsArray.append(id) } } return campaignsIdsArray.isEmpty ? "" : campaignsIdsArray.joined(separator: ", ") } func getCampaignId() -> String? { guard let campaignId = amountHelper.campaign?.id else { return nil } return "\(campaignId)" } } extension PXBusinessResultViewModel: PXViewModelTrackingDataProtocol { func getPrimaryButtonTrack() -> PXResultTrackingEvents { .didTapButton(initiative: .checkout, status: businessResult.paymentStatus, action: .primaryButton) } func getSecondaryButtonTrack() -> PXResultTrackingEvents { .didTapButton(initiative: .checkout, status: businessResult.paymentStatus, action: .secondaryButton) } func getDebinProperties() -> [String: Any]? { guard let paymentTypeId = amountHelper.getPaymentData().paymentMethod?.paymentTypeId, let paymentTypeIdEnum = PXPaymentTypes(rawValue: paymentTypeId), paymentTypeIdEnum == .BANK_TRANSFER else { return nil } var debinProperties: [String: Any] = [:] debinProperties["bank_name"] = debinBankName debinProperties["external_account_id"] = amountHelper.getPaymentData().transactionInfo?.bankInfo?.accountId return debinProperties } func getCloseButtonTrack() -> PXResultTrackingEvents { return .didTapOnCloseButton(initiative: .checkout, status: businessResult.paymentStatus) } func getTrackingPath() -> PXResultTrackingEvents? { let paymentStatus = businessResult.paymentStatus var screenPath: PXResultTrackingEvents? var properties = getTrackingProperties() if let debinProperties = getDebinProperties() { properties.merge(debinProperties) { current, _ in current } } if paymentStatus == PXPaymentStatus.APPROVED.rawValue { screenPath = .checkoutPaymentApproved(properties) } else if paymentStatus == PXPaymentStatus.IN_PROCESS.rawValue || paymentStatus == PXPaymentStatus.PENDING.rawValue { screenPath = .checkoutPaymentInProcess(properties) } else if paymentStatus == PXPaymentStatus.REJECTED.rawValue { screenPath = .checkoutPaymentRejected(properties) } else { screenPath = .checkoutPaymentUnknown(properties) } return screenPath } func getFlowBehaviourResult() -> PXResultKey { switch businessResult.getBusinessStatus() { case .APPROVED: return .SUCCESS case .REJECTED: return .FAILURE case .PENDING: return .PENDING case .IN_PROGRESS: return .PENDING } } func getTrackingProperties() -> [String: Any] { var properties: [String: Any] = amountHelper.getPaymentData().getPaymentDataForTracking() properties["style"] = "custom" if let paymentId = getPaymentId() { properties["payment_id"] = Int64(paymentId) } properties["payment_status"] = businessResult.paymentStatus properties["payment_status_detail"] = businessResult.paymentStatusDetail properties["has_split_payment"] = amountHelper.isSplitPayment properties["currency_id"] = SiteManager.shared.getCurrency().id properties["discount_coupon_amount"] = amountHelper.getDiscountCouponAmountForTracking() properties = PXCongratsTracking.getProperties(dataProtocol: self, properties: properties) if let rawAmount = amountHelper.getPaymentData().getRawAmount() { properties["total_amount"] = rawAmount.decimalValue } return properties } func getTrackingRemediesProperties(isFromModal: Bool) -> [String: Any] { var properties: [String: Any] = [:] properties["index"] = 0 properties["type"] = businessResult.getPaymentMethodTypeId() properties["payment_status"] = businessResult.paymentStatus properties["payment_status_detail"] = businessResult.getStatusDetail() properties["from"] = isFromModal == true ? "modal" : "view" return properties } func getViewErrorPaymentResult() -> [String: Any] { var properties: [String: Any] = [:] properties["index"] = 0 properties["type"] = businessResult.getPaymentMethodTypeId() properties["payment_status"] = businessResult.paymentStatus properties["payment_status_detail"] = businessResult.getStatusDetail() return properties } func getDidShowRemedyErrorModal() -> [String: Any] { var properties: [String: Any] = [:] properties["index"] = 0 properties["type"] = businessResult.getPaymentMethodTypeId() properties["payment_status"] = businessResult.paymentStatus properties["payment_status_detail"] = businessResult.getStatusDetail() return properties } }
mit
53b269daf6019dbfe7486fa7f600a750
41.756345
155
0.683248
5.334389
false
false
false
false
butterproject/butter-ios
Butter/API/ButterAPIManager.swift
1
4235
// // ButterAPIManager.swift // Butter // // Created by DjinnGA on 24/07/2015. // Copyright (c) 2015 Butter Project. All rights reserved. // import Foundation class ButterAPIManager: NSObject { static let sharedInstance = ButterAPIManager() let moviesAPIEndpoint: String = "http://vodo.net/popcorn" // ToDo: Add Vodo let moviesAPIEndpointCloudFlareHost : String = "" let TVShowsAPIEndpoint: String = "" let animeAPIEndpoint: String = "" var isSearching = false var cachedMovies = OrderedDictionary<String,ButterItem>() var cachedTVShows = OrderedDictionary<String,ButterItem>() var cachedAnime = OrderedDictionary<String,ButterItem>() var moviesPage = 0 var showsPage = 0 var searchPage = 0 static let languages = [ "ar": "Arabic", "eu": "Basque", "bs": "Bosnian", "br": "Breton", "bg": "Bulgarian", "zh": "Chinese", "hr": "Croatian", "cs": "Czech", "da": "Danish", "nl": "Dutch", "en": "English", "et": "Estonian", "fi": "Finnish", "fr": "French", "de": "German", "el": "Greek", "he": "Hebrew", "hu": "Hungarian", "it": "Italian", "lt": "Lithuanian", "mk": "Macedonian", "fa": "Persian", "pl": "Polish", "pt": "Portuguese", "ro": "Romanian", "ru": "Russian", "sr": "Serbian", "sl": "Slovene", "es": "Spanish", "sv": "Swedish", "th": "Thai", "tr": "Turkish", "uk": "Ukrainian" ] var searchResults = OrderedDictionary<String,ButterItem>() var amountToLoad: Int = 50 var mgenres: [String] = ["All"] var genres: [String] { set(newValue) { self.mgenres = newValue if (newValue[0] != "All") { isSearching = true searchPage = 0 } else { isSearching = false } } get { return self.mgenres } } var quality: String = "All" private var msearchString: String = "" var searchString: String { set(newValue) { self.msearchString = newValue.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())! searchResults = OrderedDictionary<String,ButterItem>() if (newValue != "") { isSearching = true searchPage = 0 } else { isSearching = false } } get { return self.msearchString } } func loadMovies(onCompletion: (newItems : Bool) -> Void) { var page : Int! if isSearching { page = ++searchPage } else { page = ++moviesPage } MovieAPI.sharedInstance.load(page) { (newItems) in onCompletion(newItems: newItems) } } func loadTVShows(onCompletion: (newItems : Bool) -> Void) { var page : Int! if isSearching { page = ++searchPage } else { page = ++showsPage } TVAPI.sharedInstance.load(page) { (newItems) in onCompletion(newItems: newItems) } } func loadAnime(onCompletion: () -> Void) { var page : Int! if isSearching { page = ++searchPage } else { page = ++showsPage } AnimeAPI.sharedInstance.load(page, onCompletion: { onCompletion() }) } func makeMagnetLink(torrHash:String, title: String)-> String { let torrentHash = torrHash let movieTitle = title let demoniiTracker = "udp://open.demonii.com:1337" let istoleTracker = "udp://tracker.istole.it:80" let yifyTracker = "http://tracker.yify-torrents.com/announce" let publicbtTracker = "udp://tracker.publicbt.com:80" let openBTTracker = "udp://tracker.openbittorrent.com:80" let copperTracker = "udp://tracker.coppersurfer.tk:6969" let desync1Tracker = "udp://exodus.desync.com:6969" let desync2Tracker = "http://exodus.desync.com:6969/announce" let magnetURL = "magnet:?xt=urn:btih:\(torrentHash)&dn=\(movieTitle)&tr=\(demoniiTracker)&tr=\(istoleTracker)&tr=\(yifyTracker)&tr=\(publicbtTracker)&tr=\(openBTTracker)&tr=\(copperTracker)&tr=\(desync1Tracker)&tr=\(desync2Tracker)" return magnetURL } }
gpl-3.0
f2f3157291f86c630b78a4b19477d16e
25.980892
240
0.578512
3.654012
false
false
false
false
DaftMobile/ios4beginners_2017
Class 4/Networking.playground/Pages/Threading.xcplaygroundpage/Contents.swift
1
1414
//: [Previous](@previous) import Foundation import UIKit import PlaygroundSupport //: This tells the Playground that we'll be dealing with THREADING, so that the execution doesn't stop when it reaches the end of the playground PlaygroundPage.current.needsIndefiniteExecution = true print("Starting execution") //: ### Basic background job /* DispatchQueue.global().async { // This will be executed in a background thread PlaygroundPage.current.finishExecution() } */ /* DispatchQueue.global().async { // This is a time consuming task that should be executed on a background queue to make your UI responsive var sumOfRandoms: Int32 = 0 for _ in 0..<10000 { sumOfRandoms = sumOfRandoms &+ Int32(arc4random_uniform(10000000)) } print("Finished with result \(sumOfRandoms)") PlaygroundPage.current.finishExecution() } */ //: Sometimes you need to pass a value from the background Queue to the main Queue //: WARNING: ONLY WORK WITH UIKIT APIS ON THE MAIN QUEUE /* let label = UILabel() DispatchQueue.global().async { var sumOfRandoms: Int32 = 0 for _ in 0..<10000 { sumOfRandoms = sumOfRandoms &+ Int32(arc4random_uniform(10000000)) } // label.text = "\(sumOfRandoms)" -- NEVER to this on the background queue DispatchQueue.main.async { label.text = "\(sumOfRandoms)" print("Finished and set label to \(label.text ?? "")") PlaygroundPage.current.finishExecution() } } */ //: [Next](@next)
apache-2.0
3ea4327019385d57b102aa06ca5b343f
27.857143
144
0.732673
3.906077
false
false
false
false
3drobotics/SwiftIO
Sources/TCPChannel.swift
1
11477
// // TCPChannel.swift // SwiftIO // // Created by Jonathan Wight on 6/23/15. // // Copyright (c) 2014, Jonathan Wight // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Darwin import Dispatch import SwiftUtilities public class TCPChannel: Connectable { public enum Error: ErrorType { case IncorrectState(String) case Unknown } public let label: String? public let address: Address public let state = ObservableProperty(ConnectionState.Disconnected) // MARK: Callbacks public var readCallback: (Result <DispatchData <Void>> -> Void)? { willSet { preconditionConnected() } } /// Return true from shouldReconnect to initiate a reconnect. Does not make sense on a server socket. public var shouldReconnect: (Void -> Bool)? { willSet { preconditionConnected() } } public var reconnectionDelay: NSTimeInterval = 5.0 { willSet { preconditionConnected() } } // MARK: Private properties private let queue: dispatch_queue_t private let lock = NSRecursiveLock() public private(set) var socket: Socket! private var channel: dispatch_io_t! private var disconnectCallback: (Result <Void> -> Void)? // MARK: Initialization public init(label: String? = nil, address: Address, qos: qos_class_t = QOS_CLASS_DEFAULT) { assert(address.port != nil) self.label = label self.address = address let queueAttribute = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, qos, 0) self.queue = dispatch_queue_create("io.schwa.SwiftIO.TCP.queue", queueAttribute) } public func connect(callback: Result <Void> -> Void) { connect(timeout: 30, callback: callback) } public func connect(timeout timeout: Int, callback: Result <Void> -> Void) { dispatch_async(queue) { [weak self, address] in guard let strong_self = self else { return } if strong_self.state.value != .Disconnected { callback(.Failure(Error.IncorrectState("Cannot connect channel in state \(strong_self.state.value)"))) return } log?.debug("\(strong_self): Trying to connect.") do { strong_self.state.value = .Connecting let socket: Socket socket = try Socket(domain: address.family.rawValue, type: SOCK_STREAM, protocol: IPPROTO_TCP) strong_self.configureSocket?(socket) try socket.connect(address, timeout: timeout) strong_self.socket = socket strong_self.state.value = .Connected strong_self.createStream() log?.debug("\(strong_self): Connection success.") callback(.Success()) } catch let error { strong_self.state.value = .Disconnected log?.debug("\(strong_self): Connection failure: \(error).") callback(.Failure(error)) } } } public func disconnect(callback: Result <Void> -> Void) { retrier?.cancel() retrier = nil dispatch_async(queue) { [weak self] in guard let strong_self = self else { return } if Set([.Disconnected, .Disconnecting]).contains(strong_self.state.value) { callback(.Failure(Error.IncorrectState("Cannot disconnect channel in state \(strong_self.state.value)"))) return } log?.debug("\(strong_self): Trying to disconnect.") strong_self.state.value = .Disconnecting strong_self.disconnectCallback = callback dispatch_io_close(strong_self.channel, DISPATCH_IO_STOP) } } var retrier: Retrier? = nil var retryOptions = Retrier.Options() public func connect(retryDelay retryDelay: NSTimeInterval?, retryMultiplier: Double? = nil, retryMaximumDelay: NSTimeInterval? = nil, retryMaximumAttempts: Int? = nil, callback: Result <Void> -> Void) { var options = Retrier.Options() if let retryDelay = retryDelay { options.delay = retryDelay } if let retryMultiplier = retryMultiplier { options.multiplier = retryMultiplier } if let retryMaximumDelay = retryMaximumDelay { options.maximumDelay = retryMaximumDelay } if let retryMaximumAttempts = retryMaximumAttempts { options.maximumAttempts = retryMaximumAttempts } connect(retryOptions: options, callback: callback) } private func connect(retryOptions retryOptions: Retrier.Options, callback: Result <Void> -> Void) { self.retryOptions = retryOptions let retrier = Retrier(options: retryOptions) { [weak self] (retryCallback) in guard let strong_self = self else { return } strong_self.connect() { (result: Result <Void>) -> Void in if case .Failure(let error) = result { if retryCallback(.Failure(error)) == false { log?.debug("\(strong_self): Connection retry failed with \(error).") callback(result) strong_self.retrier = nil } } else { retryCallback(.Success()) log?.debug("\(strong_self): Connection retry succeeded.") callback(result) strong_self.retrier = nil } } } self.retrier = retrier retrier.resume() } // MARK: - public func write(data: DispatchData <Void>, callback: Result <Void> -> Void) { dispatch_io_write(channel, 0, data.data, queue) { (done, data, error) in guard error == 0 else { callback(Result.Failure(Errno(rawValue: error)!)) return } callback(Result.Success()) } } private func createStream() { channel = dispatch_io_create(DISPATCH_IO_STREAM, socket.descriptor, queue) { [weak self] (error) in guard let strong_self = self else { return } tryElseFatalError() { try strong_self.handleDisconnect() } } assert(channel != nil) precondition(state.value == .Connected) dispatch_io_set_low_water(channel, 0) dispatch_io_read(channel, 0, -1 /* Int(truncatingBitPattern:SIZE_MAX) */, queue) { [weak self] (done, data, error) in guard let strong_self = self else { return } guard error == 0 else { if error == ECONNRESET { tryElseFatalError() { try strong_self.handleDisconnect() } return } strong_self.readCallback?(Result.Failure(Errno(rawValue: error)!)) return } switch (done, dispatch_data_get_size(data!) > 0) { case (false, _), (true, true): let dispatchData = DispatchData <Void> (data: data!) strong_self.readCallback?(Result.Success(dispatchData)) case (true, false): dispatch_io_close(strong_self.channel, dispatch_io_close_flags_t()) } } } private func handleDisconnect() throws { let remoteDisconnect = (state.value != .Disconnecting) try socket.close() state.value = .Disconnected if let shouldReconnect = shouldReconnect where remoteDisconnect == true { let reconnectFlag = shouldReconnect() if reconnectFlag == true { let time = dispatch_time(DISPATCH_TIME_NOW, Int64(reconnectionDelay * 1000000000)) dispatch_after(time, queue) { [weak self] (result) in guard let strong_self = self else { return } strong_self.reconnect() } return } } disconnectCallback?(Result.Success()) disconnectCallback = nil } private func reconnect() { connect(retryOptions: retryOptions) { [weak self] (result) in guard let strong_self = self else { return } if case .Failure = result { strong_self.disconnectCallback?(result) strong_self.disconnectCallback = nil } } } private func preconditionConnected() { precondition(state.value == .Disconnected, "Cannot change parameter while socket connected") } // MARK: - public var configureSocket: (Socket -> Void)? } // MARK: - extension TCPChannel { /// Create a TCPChannel from a pre-existing socket. The setup closure is called after the channel is created but before the state has changed to `Connecting`. This gives consumers a chance to configure the channel before it is fully connected. public convenience init(label: String? = nil, address: Address, socket: Socket, qos: qos_class_t = QOS_CLASS_DEFAULT, @noescape setup: (TCPChannel -> Void)) { self.init(label: label, address: address) self.socket = socket setup(self) state.value = .Connected createStream() } } // MARK: - extension TCPChannel: CustomStringConvertible { public var description: String { return "TCPChannel(label: \(label), address: \(address)), state: \(state.value))" } } // MARK: - extension TCPChannel: Hashable { public var hashValue: Int { return ObjectIdentifier(self).hashValue } } public func == (lhs: TCPChannel, rhs: TCPChannel) -> Bool { return lhs === rhs }
mit
71dfa139c02e4ef88ce01f5d8e9b4f28
32.266667
247
0.583079
4.892157
false
false
false
false
KeithPiTsui/Pavers
Pavers/Sources/Argo/Types/DecodeError.swift
1
2145
/// Possible decoding failure reasons. public enum DecodeError: Error { /// The type existing at the key didn't match the type being requested. case typeMismatch(expected: String, actual: String) /// The key did not exist in the JSON. case missingKey(String) /// A custom error case for adding explicit failure info. case custom(String) /// There were multiple errors in the JSON. case multiple([DecodeError]) } extension DecodeError: CustomStringConvertible { public var description: String { switch self { case let .typeMismatch(expected, actual): return "TypeMismatch(Expected \(expected), got \(actual))" case let .missingKey(s): return "MissingKey(\(s))" case let .custom(s): return "Custom(\(s))" case let .multiple(es): return "Multiple(\(es.map { $0.description }.joined(separator: ", ")))" } } } extension DecodeError: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(self.hashValue) } public var hashValue: Int { switch self { case let .typeMismatch(expected: expected, actual: actual): return expected.hashValue ^ actual.hashValue case let .missingKey(string): return string.hashValue case let .custom(string): return string.hashValue case let .multiple(es): return es.reduce(0) { $0 ^ $1.hashValue } } } } public func == (lhs: DecodeError, rhs: DecodeError) -> Bool { switch (lhs, rhs) { case let (.typeMismatch(expected: expected1, actual: actual1), .typeMismatch(expected: expected2, actual: actual2)): return expected1 == expected2 && actual1 == actual2 case let (.missingKey(string1), .missingKey(string2)): return string1 == string2 case let (.custom(string1), .custom(string2)): return string1 == string2 case let (.multiple(lhs), .multiple(rhs)): return lhs == rhs default: return false } } public func + (lhs: DecodeError, rhs: DecodeError) -> DecodeError { switch (lhs, rhs) { case let (.multiple(es), e): return .multiple(es + [e]) case let (e, .multiple(es)): return .multiple([e] + es) case let (le, re): return .multiple([le, re]) } }
mit
b71cb1be63cee2997ec9ac30c7fd3c5d
29.211268
118
0.671795
3.972222
false
false
false
false
renjithk/ios-charts
Charts/Classes/Charts/ChartViewBase.swift
9
34333
// // ChartViewBase.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // // Based on https://github.com/PhilJay/MPAndroidChart/commit/c42b880 import Foundation import UIKit @objc public protocol ChartViewDelegate { /// Called when a value has been selected inside the chart. /// :entry: The selected Entry. /// :dataSetIndex: The index in the datasets array of the data object the Entrys DataSet is in. optional func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: ChartHighlight) // Called when nothing has been selected or an "un-select" has been made. optional func chartValueNothingSelected(chartView: ChartViewBase) // Callbacks when the chart is scaled / zoomed via pinch zoom gesture. optional func chartScaled(chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat) // Callbacks when the chart is moved / translated via drag gesture. optional func chartTranslated(chartView: ChartViewBase, dX: CGFloat, dY: CGFloat) } public class ChartViewBase: UIView, ChartAnimatorDelegate { // MARK: - Properties /// custom formatter that is used instead of the auto-formatter if set internal var _valueFormatter = NSNumberFormatter() /// the default value formatter internal var _defaultValueFormatter = NSNumberFormatter() /// object that holds all data that was originally set for the chart, before it was modified or any filtering algorithms had been applied internal var _data: ChartData! /// If set to true, chart continues to scroll after touch up public var dragDecelerationEnabled = true /// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately. /// 1 is an invalid value, and will be converted to 0.999 automatically. private var _dragDecelerationFrictionCoef: CGFloat = 0.9 /// font object used for drawing the description text in the bottom right corner of the chart public var descriptionFont: UIFont? = UIFont(name: "HelveticaNeue", size: 9.0) public var descriptionTextColor: UIColor! = UIColor.blackColor() /// font object for drawing the information text when there are no values in the chart public var infoFont: UIFont! = UIFont(name: "HelveticaNeue", size: 12.0) public var infoTextColor: UIColor! = UIColor(red: 247.0/255.0, green: 189.0/255.0, blue: 51.0/255.0, alpha: 1.0) // orange /// description text that appears in the bottom right corner of the chart public var descriptionText = "Description" /// flag that indicates if the chart has been fed with data yet internal var _dataNotSet = true /// if true, units are drawn next to the values in the chart internal var _drawUnitInChart = false /// the number of x-values the chart displays internal var _deltaX = CGFloat(1.0) internal var _chartXMin = Double(0.0) internal var _chartXMax = Double(0.0) /// the legend object containing all data associated with the legend internal var _legend: ChartLegend! /// delegate to receive chart events public weak var delegate: ChartViewDelegate? /// text that is displayed when the chart is empty public var noDataText = "No chart data available." /// text that is displayed when the chart is empty that describes why the chart is empty public var noDataTextDescription: String? internal var _legendRenderer: ChartLegendRenderer! /// object responsible for rendering the data public var renderer: ChartDataRendererBase? /// object that manages the bounds and drawing constraints of the chart internal var _viewPortHandler: ChartViewPortHandler! /// object responsible for animations internal var _animator: ChartAnimator! /// flag that indicates if offsets calculation has already been done or not private var _offsetsCalculated = false /// array of Highlight objects that reference the highlighted slices in the chart internal var _indicesToHightlight = [ChartHighlight]() /// if set to true, the marker is drawn when a value is clicked public var drawMarkers = true /// the view that represents the marker public var marker: ChartMarker? private var _interceptTouchEvents = false /// An extra offset to be appended to the viewport's top public var extraTopOffset: CGFloat = 0.0 /// An extra offset to be appended to the viewport's right public var extraRightOffset: CGFloat = 0.0 /// An extra offset to be appended to the viewport's bottom public var extraBottomOffset: CGFloat = 0.0 /// An extra offset to be appended to the viewport's left public var extraLeftOffset: CGFloat = 0.0 public func setExtraOffsets(#left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) { extraLeftOffset = left extraTopOffset = top extraRightOffset = right extraBottomOffset = bottom } // MARK: - Initializers public override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clearColor() initialize() } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } deinit { self.removeObserver(self, forKeyPath: "bounds") self.removeObserver(self, forKeyPath: "frame") } internal func initialize() { _animator = ChartAnimator() _animator.delegate = self _viewPortHandler = ChartViewPortHandler() _viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height) _legend = ChartLegend() _legendRenderer = ChartLegendRenderer(viewPortHandler: _viewPortHandler, legend: _legend) _defaultValueFormatter.minimumIntegerDigits = 1 _defaultValueFormatter.maximumFractionDigits = 1 _defaultValueFormatter.minimumFractionDigits = 1 _defaultValueFormatter.usesGroupingSeparator = true _valueFormatter = _defaultValueFormatter.copy() as! NSNumberFormatter self.addObserver(self, forKeyPath: "bounds", options: .New, context: nil) self.addObserver(self, forKeyPath: "frame", options: .New, context: nil) } // MARK: - ChartViewBase /// The data for the chart public var data: ChartData? { get { return _data } set { if (newValue == nil || newValue?.yValCount == 0) { println("Charts: data argument is nil on setData()") return } _dataNotSet = false _offsetsCalculated = false _data = newValue // calculate how many digits are needed calculateFormatter(min: _data.getYMin(), max: _data.getYMax()) notifyDataSetChanged() } } /// Clears the chart from all data (sets it to null) and refreshes it (by calling setNeedsDisplay()). public func clear() { _data = nil _dataNotSet = true setNeedsDisplay() } /// Removes all DataSets (and thereby Entries) from the chart. Does not remove the x-values. Also refreshes the chart by calling setNeedsDisplay(). public func clearValues() { if (_data !== nil) { _data.clearValues() } setNeedsDisplay() } /// Returns true if the chart is empty (meaning it's data object is either null or contains no entries). public func isEmpty() -> Bool { if (_data == nil) { return true } else { if (_data.yValCount <= 0) { return true } else { return false } } } /// Lets the chart know its underlying data has changed and should perform all necessary recalculations. public func notifyDataSetChanged() { fatalError("notifyDataSetChanged() cannot be called on ChartViewBase") } /// calculates the offsets of the chart to the border depending on the position of an eventual legend or depending on the length of the y-axis and x-axis labels and their position internal func calculateOffsets() { fatalError("calculateOffsets() cannot be called on ChartViewBase") } /// calcualtes the y-min and y-max value and the y-delta and x-delta value internal func calcMinMax() { fatalError("calcMinMax() cannot be called on ChartViewBase") } /// calculates the required number of digits for the values that might be drawn in the chart (if enabled), and creates the default value formatter internal func calculateFormatter(#min: Double, max: Double) { // check if a custom formatter is set or not var reference = Double(0.0) if (_data == nil || _data.xValCount < 2) { var absMin = fabs(min) var absMax = fabs(max) reference = absMin > absMax ? absMin : absMax } else { reference = fabs(max - min) } var digits = ChartUtils.decimals(reference) _defaultValueFormatter.maximumFractionDigits = digits _defaultValueFormatter.minimumFractionDigits = digits } public override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() let frame = self.bounds if (_dataNotSet || _data === nil || _data.yValCount == 0) { // check if there is data CGContextSaveGState(context) // if no data, inform the user ChartUtils.drawText(context: context, text: noDataText, point: CGPoint(x: frame.width / 2.0, y: frame.height / 2.0), align: .Center, attributes: [NSFontAttributeName: infoFont, NSForegroundColorAttributeName: infoTextColor]) if (noDataTextDescription != nil && count(noDataTextDescription!) > 0) { var textOffset = -infoFont.lineHeight / 2.0 ChartUtils.drawText(context: context, text: noDataTextDescription!, point: CGPoint(x: frame.width / 2.0, y: frame.height / 2.0 + textOffset), align: .Center, attributes: [NSFontAttributeName: infoFont, NSForegroundColorAttributeName: infoTextColor]) } return } if (!_offsetsCalculated) { calculateOffsets() _offsetsCalculated = true } } /// draws the description text in the bottom right corner of the chart internal func drawDescription(#context: CGContext) { if (descriptionText.lengthOfBytesUsingEncoding(NSUTF16StringEncoding) == 0) { return } let frame = self.bounds var attrs = [NSObject: AnyObject]() var font = descriptionFont if (font == nil) { font = UIFont.systemFontOfSize(UIFont.systemFontSize()) } attrs[NSFontAttributeName] = font attrs[NSForegroundColorAttributeName] = descriptionTextColor ChartUtils.drawText(context: context, text: descriptionText, point: CGPoint(x: frame.width - _viewPortHandler.offsetRight - 10.0, y: frame.height - _viewPortHandler.offsetBottom - 10.0 - font!.lineHeight), align: .Right, attributes: attrs) } // MARK: - Highlighting /// Returns the array of currently highlighted values. This might be null or empty if nothing is highlighted. public var highlighted: [ChartHighlight] { return _indicesToHightlight } /// Returns true if there are values to highlight, /// false if there are no values to highlight. /// Checks if the highlight array is null, has a length of zero or if the first object is null. public func valuesToHighlight() -> Bool { return _indicesToHightlight.count > 0 } /// Highlights the values at the given indices in the given DataSets. Provide /// null or an empty array to undo all highlighting. /// This should be used to programmatically highlight values. /// This DOES NOT generate a callback to the delegate. public func highlightValues(highs: [ChartHighlight]?) { // set the indices to highlight _indicesToHightlight = highs ?? [ChartHighlight]() if (_indicesToHightlight.isEmpty) { self.lastHighlighted = nil } // redraw the chart setNeedsDisplay() } /// Highlights the value at the given x-index in the given DataSet. /// Provide -1 as the x-index to undo all highlighting. public func highlightValue(#xIndex: Int, dataSetIndex: Int, callDelegate: Bool) { if (xIndex < 0 || dataSetIndex < 0 || xIndex >= _data.xValCount || dataSetIndex >= _data.dataSetCount) { highlightValue(highlight: nil, callDelegate: callDelegate) } else { highlightValue(highlight: ChartHighlight(xIndex: xIndex, dataSetIndex: dataSetIndex), callDelegate: callDelegate) } } /// Highlights the value selected by touch gesture. public func highlightValue(#highlight: ChartHighlight?, callDelegate: Bool) { var entry: ChartDataEntry? var h = highlight if (h == nil) { _indicesToHightlight.removeAll(keepCapacity: false) } else { // set the indices to highlight entry = _data.getEntryForHighlight(h!) if (entry === nil || entry!.xIndex != h?.xIndex) { h = nil entry = nil _indicesToHightlight.removeAll(keepCapacity: false) } else { _indicesToHightlight = [h!] } } // redraw the chart setNeedsDisplay() if (callDelegate && delegate != nil) { if (h == nil) { delegate!.chartValueNothingSelected?(self) } else { // notify the listener delegate!.chartValueSelected?(self, entry: entry!, dataSetIndex: h!.dataSetIndex, highlight: h!) } } } /// The last value that was highlighted via touch. public var lastHighlighted: ChartHighlight? // MARK: - Markers /// draws all MarkerViews on the highlighted positions internal func drawMarkers(#context: CGContext) { // if there is no marker view or drawing marker is disabled if (marker === nil || !drawMarkers || !valuesToHighlight()) { return } for (var i = 0, count = _indicesToHightlight.count; i < count; i++) { let highlight = _indicesToHightlight[i] let xIndex = highlight.xIndex let dataSetIndex = highlight.dataSetIndex if (xIndex <= Int(_deltaX) && xIndex <= Int(_deltaX * _animator.phaseX)) { let e = _data.getEntryForHighlight(highlight) if (e === nil || e!.xIndex != highlight.xIndex) { continue } var pos = getMarkerPosition(entry: e!, dataSetIndex: dataSetIndex) // check bounds if (!_viewPortHandler.isInBounds(x: pos.x, y: pos.y)) { continue } // callbacks to update the content marker!.refreshContent(entry: e!, dataSetIndex: dataSetIndex) let markerSize = marker!.size if (pos.y - markerSize.height <= 0.0) { let y = markerSize.height - pos.y marker!.draw(context: context, point: CGPoint(x: pos.x, y: pos.y + y)) } else { marker!.draw(context: context, point: pos) } } } } /// Returns the actual position in pixels of the MarkerView for the given Entry in the given DataSet. public func getMarkerPosition(#entry: ChartDataEntry, dataSetIndex: Int) -> CGPoint { fatalError("getMarkerPosition() cannot be called on ChartViewBase") } // MARK: - Animation /// Returns the animator responsible for animating chart values. public var animator: ChartAnimator! { return _animator } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: xAxisDuration duration for animating the x axis /// :param: yAxisDuration duration for animating the y axis /// :param: easingX an easing function for the animation on the x axis /// :param: easingY an easing function for the animation on the y axis public func animate(#xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingX, easingY: easingY) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: xAxisDuration duration for animating the x axis /// :param: yAxisDuration duration for animating the y axis /// :param: easingOptionX the easing function for the animation on the x axis /// :param: easingOptionY the easing function for the animation on the y axis public func animate(#xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOptionX: easingOptionX, easingOptionY: easingOptionY) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: xAxisDuration duration for animating the x axis /// :param: yAxisDuration duration for animating the y axis /// :param: easing an easing function for the animation public func animate(#xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easing) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: xAxisDuration duration for animating the x axis /// :param: yAxisDuration duration for animating the y axis /// :param: easingOption the easing function for the animation public func animate(#xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: easingOption) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: xAxisDuration duration for animating the x axis /// :param: yAxisDuration duration for animating the y axis public func animate(#xAxisDuration: NSTimeInterval, yAxisDuration: NSTimeInterval) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: xAxisDuration duration for animating the x axis /// :param: easing an easing function for the animation public func animate(#xAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, easing: easing) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: xAxisDuration duration for animating the x axis /// :param: easingOption the easing function for the animation public func animate(#xAxisDuration: NSTimeInterval, easingOption: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, easingOption: easingOption) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: xAxisDuration duration for animating the x axis public func animate(#xAxisDuration: NSTimeInterval) { _animator.animate(xAxisDuration: xAxisDuration) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: yAxisDuration duration for animating the y axis /// :param: easing an easing function for the animation public func animate(#yAxisDuration: NSTimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(yAxisDuration: yAxisDuration, easing: easing) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: yAxisDuration duration for animating the y axis /// :param: easingOption the easing function for the animation public func animate(#yAxisDuration: NSTimeInterval, easingOption: ChartEasingOption) { _animator.animate(yAxisDuration: yAxisDuration, easingOption: easingOption) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If animate(...) is called, no further calling of invalidate() is necessary to refresh the chart. /// :param: yAxisDuration duration for animating the y axis public func animate(#yAxisDuration: NSTimeInterval) { _animator.animate(yAxisDuration: yAxisDuration) } // MARK: - Accessors /// returns the total value (sum) of all y-values across all DataSets public var yValueSum: Double { return _data.yValueSum } /// returns the current y-max value across all DataSets public var chartYMax: Double { return _data.yMax } /// returns the current y-min value across all DataSets public var chartYMin: Double { return _data.yMin } public var chartXMax: Double { return _chartXMax } public var chartXMin: Double { return _chartXMin } /// returns the average value of all values the chart holds public func getAverage() -> Double { return yValueSum / Double(_data.yValCount) } /// returns the average value for a specific DataSet (with a specific label) in the chart public func getAverage(#dataSetLabel: String) -> Double { var ds = _data.getDataSetByLabel(dataSetLabel, ignorecase: true) if (ds == nil) { return 0.0 } return ds!.yValueSum / Double(ds!.entryCount) } /// returns the total number of values the chart holds (across all DataSets) public var getValueCount: Int { return _data.yValCount } /// Returns the center point of the chart (the whole View) in pixels. /// Note: (Equivalent of getCenter() in MPAndroidChart, as center is already a standard in iOS that returns the center point relative to superview, and MPAndroidChart returns relative to self) public var midPoint: CGPoint { var bounds = self.bounds return CGPoint(x: bounds.origin.x + bounds.size.width / 2.0, y: bounds.origin.y + bounds.size.height / 2.0) } /// Returns the center of the chart taking offsets under consideration. (returns the center of the content rectangle) public var centerOffsets: CGPoint { return _viewPortHandler.contentCenter } /// Returns the Legend object of the chart. This method can be used to get an instance of the legend in order to customize the automatically generated Legend. public var legend: ChartLegend { return _legend } /// Returns the renderer object responsible for rendering / drawing the Legend. public var legendRenderer: ChartLegendRenderer! { return _legendRenderer } /// Returns the rectangle that defines the borders of the chart-value surface (into which the actual values are drawn). public var contentRect: CGRect { return _viewPortHandler.contentRect } /// Sets the formatter to be used for drawing the values inside the chart. /// If no formatter is set, the chart will automatically determine a reasonable /// formatting (concerning decimals) for all the values that are drawn inside /// the chart. Set this to nil to re-enable auto formatting. public var valueFormatter: NSNumberFormatter! { get { return _valueFormatter } set { if (newValue === nil) { _valueFormatter = _defaultValueFormatter.copy() as! NSNumberFormatter } else { _valueFormatter = newValue } } } /// returns the x-value at the given index public func getXValue(index: Int) -> String! { if (_data == nil || _data.xValCount <= index) { return nil } else { return _data.xVals[index] } } /// Get all Entry objects at the given index across all DataSets. public func getEntriesAtIndex(xIndex: Int) -> [ChartDataEntry] { var vals = [ChartDataEntry]() for (var i = 0, count = _data.dataSetCount; i < count; i++) { var set = _data.getDataSetByIndex(i) var e = set.entryForXIndex(xIndex) if (e !== nil) { vals.append(e!) } } return vals } /// returns the percentage the given value has of the total y-value sum public func percentOfTotal(val: Double) -> Double { return val / _data.yValueSum * 100.0 } /// Returns the ViewPortHandler of the chart that is responsible for the /// content area of the chart and its offsets and dimensions. public var viewPortHandler: ChartViewPortHandler! { return _viewPortHandler } /// Returns the bitmap that represents the chart. public func getChartImage(#transparent: Bool) -> UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, opaque || !transparent, UIScreen.mainScreen().scale) var context = UIGraphicsGetCurrentContext() var rect = CGRect(origin: CGPoint(x: 0, y: 0), size: bounds.size) if (opaque || !transparent) { // Background color may be partially transparent, we must fill with white if we want to output an opaque image CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor) CGContextFillRect(context, rect) if (self.backgroundColor !== nil) { CGContextSetFillColorWithColor(context, self.backgroundColor?.CGColor) CGContextFillRect(context, rect) } } layer.renderInContext(UIGraphicsGetCurrentContext()) var image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } public enum ImageFormat { case JPEG case PNG } /// Saves the current chart state with the given name to the given path on /// the sdcard leaving the path empty "" will put the saved file directly on /// the SD card chart is saved as a PNG image, example: /// saveToPath("myfilename", "foldername1/foldername2") /// /// :filePath: path to the image to save /// :format: the format to save /// :compressionQuality: compression quality for lossless formats (JPEG) /// /// :returns: true if the image was saved successfully public func saveToPath(path: String, format: ImageFormat, compressionQuality: Double) -> Bool { var image = getChartImage(transparent: format != .JPEG) var imageData: NSData! switch (format) { case .PNG: imageData = UIImagePNGRepresentation(image) break case .JPEG: imageData = UIImageJPEGRepresentation(image, CGFloat(compressionQuality)) break } return imageData.writeToFile(path, atomically: true) } /// Saves the current state of the chart to the camera roll public func saveToCameraRoll() { UIImageWriteToSavedPhotosAlbum(getChartImage(transparent: false), nil, nil, nil) } internal typealias VoidClosureType = () -> () internal var _sizeChangeEventActions = [VoidClosureType]() override public func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject: AnyObject], context: UnsafeMutablePointer<Void>) { if (keyPath == "bounds" || keyPath == "frame") { var bounds = self.bounds if (_viewPortHandler !== nil && (bounds.size.width != _viewPortHandler.chartWidth || bounds.size.height != _viewPortHandler.chartHeight)) { _viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height) // Finish any pending viewport changes while (!_sizeChangeEventActions.isEmpty) { _sizeChangeEventActions.removeAtIndex(0)() } notifyDataSetChanged() } } } public func clearPendingViewPortChanges() { _sizeChangeEventActions.removeAll(keepCapacity: false) } /// if true, value highlighting is enabled public var highlightEnabled: Bool { get { return _data === nil ? true : _data.highlightEnabled } set { if (_data !== nil) { _data.highlightEnabled = newValue } } } /// if true, value highlightning is enabled public var isHighlightEnabled: Bool { return highlightEnabled } /// :returns: true if chart continues to scroll after touch up, false if not. /// :default: true public var isDragDecelerationEnabled: Bool { return dragDecelerationEnabled } /// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately. /// 1 is an invalid value, and will be converted to 0.999 automatically. /// :default: true public var dragDecelerationFrictionCoef: CGFloat { get { return _dragDecelerationFrictionCoef } set { var val = newValue if (val < 0.0) { val = 0.0 } if (val >= 1.0) { val = 0.999 } _dragDecelerationFrictionCoef = val } } // MARK: - ChartAnimatorDelegate public func chartAnimatorUpdated(chartAnimator: ChartAnimator) { setNeedsDisplay() } public func chartAnimatorStopped(chartAnimator: ChartAnimator) { } // MARK: - Touches public override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { if (!_interceptTouchEvents) { super.touchesBegan(touches, withEvent: event) } } public override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { if (!_interceptTouchEvents) { super.touchesMoved(touches, withEvent: event) } } public override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { if (!_interceptTouchEvents) { super.touchesEnded(touches, withEvent: event) } } public override func touchesCancelled(touches: Set<NSObject>, withEvent event: UIEvent) { if (!_interceptTouchEvents) { super.touchesCancelled(touches, withEvent: event) } } }
apache-2.0
f7263cd1d7290ea53f329db9366ff0f6
34.914226
265
0.622171
5.351153
false
false
false
false
carabina/SAWaveToast
SAWaveToast/SAWaveView.swift
1
2649
// // SAWaveView.swift // SAWaveToast // // Created by Taiki Suzuki on 2015/08/31. // // import UIKit class SAWaveView: UIView { static let Height: CGFloat = 10 private let shapeLayer: CAShapeLayer = CAShapeLayer() var color: UIColor? { didSet { shapeLayer.strokeColor = color?.CGColor shapeLayer.fillColor = color?.CGColor } } init() { super.init(frame: CGRectZero) layer.addSublayer(shapeLayer) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit {} override func layoutSubviews() { super.layoutSubviews() shapeLayer.frame = CGRect(x: 0, y: 0, width: bounds.size.width * 2, height: bounds.size.height) } override func animationDidStop(anim: CAAnimation!, finished flag: Bool) { shapeLayer.removeAllAnimations() if flag { startAnimation() } } } //MARK: Private Methods extension SAWaveView { private func wavePath() -> CGPath { let path = UIBezierPath() path.moveToPoint(CGPoint(x: 0, y: frame.height * 0.5)) path.addQuadCurveToPoint(CGPoint(x: frame.width * 0.5, y: frame.height * 0.5), controlPoint: CGPoint(x: frame.width * 0.25, y: -frame.height * 0.5)) path.addQuadCurveToPoint(CGPoint(x: frame.width * 1, y: frame.height * 0.5), controlPoint: CGPoint(x: frame.width * 0.75, y: frame.height * 1.5)) path.addQuadCurveToPoint(CGPoint(x: frame.width * 1.5, y: frame.height * 0.5), controlPoint: CGPoint(x: frame.width * 1.25, y: -frame.height * 0.5)) path.addQuadCurveToPoint(CGPoint(x: frame.width * 2, y: frame.height * 0.5), controlPoint: CGPoint(x: frame.width * 1.75, y: frame.height * 1.5)) path.addLineToPoint(CGPoint(x: frame.width * 2, y: frame.height)) path.addLineToPoint(CGPoint(x: 0, y: frame.height)) path.addLineToPoint(CGPoint(x: 0, y: frame.height * 0.5)) return path.CGPath } } //MARK: Internal Methods extension SAWaveView { func startAnimation() { shapeLayer.path = wavePath() let animation = CABasicAnimation(keyPath: "position.x") animation.fromValue = 0 animation.toValue = frame.size.width animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.removedOnCompletion = false animation.duration = 1 animation.delegate = self animation.fillMode = kCAFillModeForwards shapeLayer.addAnimation(animation, forKey: "move") } }
mit
05cb0b7c015572c3c0d181b1bd66eac5
32.125
156
0.629672
4.132605
false
false
false
false
juliaguo/shakeWake
shakeWake/BLE.swift
1
10405
/* Copyright (c) 2015 Fernando Reynoso Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import CoreBluetooth public enum BLEState : Int, CustomStringConvertible { case unknown case resetting case unsupported case unauthorized case poweredOff case poweredOn public var description: String { switch self { case .unknown: return "Unknown" case .resetting: return "Resetting" case .unsupported: return "Unsupported" case .unauthorized: return "Unauthorized" case .poweredOff: return "Powered off" case .poweredOn: return "Powered on" } } } extension CBManagerState: CustomStringConvertible { public var description: String { switch self { case .unknown: return "Unknown" case .resetting: return "Resetting" case .unsupported: return "Unsupported" case .unauthorized: return "Unauthorized" case .poweredOff: return "Powered off" case .poweredOn: return "Powered on" } } } protocol BLEDelegate { func ble(didUpdateState state: BLEState) func ble(didDiscoverPeripheral peripheral: CBPeripheral) func ble(didConnectToPeripheral peripheral: CBPeripheral) func ble(didDisconnectFromPeripheral peripheral: CBPeripheral) func ble(_ peripheral: CBPeripheral, didReceiveData data: Data?) func ble(_ peripheral: CBPeripheral, didUpdateRSSI: NSNumber?) } private extension CBUUID { enum RedBearUUID: String { case service = "713D0000-503E-4C75-BA94-3148F18D941E" case charTx = "713D0002-503E-4C75-BA94-3148F18D941E" case charRx = "713D0003-503E-4C75-BA94-3148F18D941E" } convenience init(redBearType: RedBearUUID) { self.init(string:redBearType.rawValue) } } class BLE: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate { let RBL_SERVICE_UUID = "713D0000-503E-4C75-BA94-3148F18D941E" let RBL_CHAR_TX_UUID = "713D0002-503E-4C75-BA94-3148F18D941E" let RBL_CHAR_RX_UUID = "713D0003-503E-4C75-BA94-3148F18D941E" var delegate: BLEDelegate? private var centralManager: CBCentralManager! private var activePeripheral: CBPeripheral? private var activeRSSI: NSNumber? private var characteristics = [String : CBCharacteristic]() private var data: NSMutableData? private(set) var peripherals = [CBPeripheral]() private var RSSICompletionHandler: ((NSNumber?, Error?) -> ())? override init() { super.init() self.centralManager = CBCentralManager(delegate: self, queue: nil) self.data = NSMutableData() } @objc private func scanTimeout() { print("[DEBUG] Scanning stopped") self.centralManager.stopScan() } // MARK: Public methods func startScanning(timeout: Double) -> Bool { if centralManager.state != .poweredOn { print("[ERROR] Couldn´t start scanning") return false } print("[DEBUG] Scanning started") // CBCentralManagerScanOptionAllowDuplicatesKey Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(BLE.scanTimeout), userInfo: nil, repeats: false) let services:[CBUUID] = [CBUUID(redBearType: .service)] centralManager.scanForPeripherals(withServices: services, options: nil) return true } func stopScanning() { centralManager.stopScan() } func connectToPeripheral(_ peripheral: CBPeripheral) -> Bool { if centralManager.state != .poweredOn { print("[ERROR] Couldn´t connect to peripheral") return false } print("[DEBUG] Connecting to peripheral: \(peripheral.identifier.uuidString)") centralManager.connect(peripheral, options: [CBConnectPeripheralOptionNotifyOnDisconnectionKey : NSNumber(value: true)]) return true } func disconnectFromPeripheral(_ peripheral: CBPeripheral) -> Bool { if centralManager.state != .poweredOn { print("[ERROR] Couldn´t disconnect from peripheral") return false } centralManager.cancelPeripheralConnection(peripheral) return true } func read() { guard let char = characteristics[RBL_CHAR_TX_UUID] else { return } activePeripheral?.readValue(for: char) } func write(data: NSData) { guard let char = characteristics[RBL_CHAR_RX_UUID] else { return } activePeripheral?.writeValue(data as Data, for: char, type: .withoutResponse) } func enableNotifications(enable: Bool) { guard let char = characteristics[RBL_CHAR_TX_UUID] else { return } activePeripheral?.setNotifyValue(enable, for: char) } func readRSSI(completion: @escaping (_ RSSI: NSNumber?, _ error: Error?) -> ()) { RSSICompletionHandler = completion activePeripheral?.readRSSI() } // MARK: CBCentralManager delegate func centralManagerDidUpdateState(_ central: CBCentralManager) { print("[DEBUG] Central manager state: \(central.state)") delegate?.ble(didUpdateState: BLEState(rawValue: central.state.rawValue)!) } func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { print("[DEBUG] Find peripheral: \(peripheral.identifier.uuidString) RSSI: \(RSSI)") print(advertisementData["kCBAdvDataServiceUUIDs"]) let index = peripherals.index { $0.identifier.uuidString == peripheral.identifier.uuidString } if let index = index { peripherals[index] = peripheral } else { peripherals.append(peripheral) } delegate?.ble(didDiscoverPeripheral: peripheral) } func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { print("[ERROR] Could not connect to peripheral \(peripheral.identifier.uuidString) error: \(error!.localizedDescription)") } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { print("[DEBUG] Connected to peripheral \(peripheral.identifier.uuidString)") activePeripheral = peripheral activePeripheral?.delegate = self activePeripheral?.discoverServices([CBUUID(redBearType: .service)]) delegate?.ble(didConnectToPeripheral: peripheral) } func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { var text = "[DEBUG] Disconnected from peripheral: \(peripheral.identifier.uuidString)" if error != nil { text += ". Error: \(error!.localizedDescription)" } print(text) activePeripheral?.delegate = nil activePeripheral = nil characteristics.removeAll(keepingCapacity: false) delegate?.ble(didDisconnectFromPeripheral: peripheral) } // MARK: CBPeripheral delegate func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { if error != nil { print("[ERROR] Error discovering services. \(error!.localizedDescription)") return } print("[DEBUG] Found services for peripheral: \(peripheral.identifier.uuidString)") for service in peripheral.services! { let theCharacteristics = [CBUUID(redBearType: .charRx), CBUUID(redBearType: .charTx)] peripheral.discoverCharacteristics(theCharacteristics, for: service) } } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { if error != nil { print("[ERROR] Error discovering characteristics. \(error!.localizedDescription)") return } print("[DEBUG] Found characteristics for peripheral: \(peripheral.identifier.uuidString)") for characteristic in service.characteristics! { characteristics[characteristic.uuid.uuidString] = characteristic } enableNotifications(enable: true) } func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { if error != nil { print("[ERROR] Error updating value. \(error!.localizedDescription)") return } if characteristic.uuid.uuidString == RBL_CHAR_TX_UUID { delegate?.ble(peripheral, didReceiveData: characteristic.value as Data?) } } func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) { activeRSSI = RSSI RSSICompletionHandler?(RSSI, error) RSSICompletionHandler = nil delegate?.ble(peripheral, didUpdateRSSI: RSSI) } }
mit
7424490370862ac72a00e611b2f0f5ad
35.756184
461
0.645741
5.317996
false
false
false
false
coodly/SlimTimerAPI
Sources/Logging.swift
1
1126
/* * Copyright 2017 Coodly 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 public protocol Logger { func log<T>(_ object: T, file: String, function: String, line: Int) } public class Logging { private var logger: Logger? private static let sharedInstance = Logging() public class func set(logger: Logger) { sharedInstance.logger = logger } internal class func log<T>(_ object: T, file: String = #file, function: String = #function, line: Int = #line) { sharedInstance.logger?.log(object, file: file, function: function, line: line) } }
apache-2.0
83337c63b09f6b7846c1bff6af2e56f9
32.117647
116
0.70071
4.124542
false
false
false
false
adrfer/swift
test/Interpreter/layout_reabstraction.swift
14
2320
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test struct S {} struct Q {} func printMetatype<T>(x: Any, _: T.Type) { debugPrint(x as! T.Type) } func printMetatypeConditional<T>(x: Any, _: T.Type) { if let y = x as? T.Type { debugPrint(y) } else { print("nope") } } var any: Any = S.self // CHECK: downcast in substituted context: print("downcast in substituted context:") // CHECK-NEXT: main.S debugPrint(any as! S.Type) // CHECK-NEXT: nope if let q = any as? Q.Type { print(q) } else { print("nope") } // CHECK-NEXT: downcast in generic context: print("downcast in generic context:") // CHECK-NEXT: main.S printMetatype(any, S.self) // CHECK-NEXT: main.S printMetatypeConditional(any, S.self) // CHECK-NEXT: nope printMetatypeConditional(any, Q.self) // Unspecialized wrapper around sizeof(T) to force us to get the runtime's idea // of the size of a type. @inline(never) func unspecializedSizeOf<T>(t: T.Type) -> Int { return sizeof(t) } struct ContainsTrivialMetatype<T> { var x: T var meta: S.Type } struct ContainsTupleOfTrivialMetatype<T> { var x: (T, S.Type) } // CHECK-NEXT: 8 print(sizeof(ContainsTrivialMetatype<Int64>.self)) // CHECK-NEXT: 8 print(unspecializedSizeOf(ContainsTrivialMetatype<Int64>.self)) // CHECK-NEXT: 8 print(sizeof(ContainsTupleOfTrivialMetatype<Int64>.self)) // CHECK-NEXT: 8 print(unspecializedSizeOf(ContainsTupleOfTrivialMetatype<Int64>.self)) struct ContainsTupleOfFunctions<T> { var x: (T, T -> T) func apply() -> T { return x.1(x.0) } } // CHECK-NEXT: 2 print(sizeof(ContainsTupleOfFunctions<()>.self) / sizeof(Int.self)) // CHECK-NEXT: 2 print(unspecializedSizeOf(ContainsTupleOfFunctions<()>.self) / sizeof(Int.self)) // CHECK-NEXT: 3 print(sizeof(ContainsTupleOfFunctions<Int>.self) / sizeof(Int.self)) // CHECK-NEXT: 3 print(unspecializedSizeOf(ContainsTupleOfFunctions<Int>.self) / sizeof(Int.self)) let x = ContainsTupleOfFunctions(x: (1, { $0 + 1 })) let y = ContainsTupleOfFunctions(x: ("foo", { $0 + "bar" })) // CHECK-NEXT: 2 print(x.apply()) // CHECK-NEXT: foobar print(y.apply()) func callAny<T>(f: Any, _ x: T) -> T { return (f as! T -> T)(x) } any = {(x: Int) -> Int in x + x} // CHECK-NEXT: 24 print((any as! Int -> Int)(12)) // CHECK-NEXT: 24 let ca = callAny(any, 12) print(ca)
apache-2.0
7337a3b060226647ec02f99054446ed6
22.2
81
0.682328
3.03268
false
false
false
false
BranchMetrics/iOS-Deferred-Deep-Linking-SDK
Branch-TestBed-Swift/TestBed-Swift/HomeViewController.swift
1
24605
// // HomeViewController.swift // TestBed-Swift // // Created by David Westgate on 8/29/16. // Copyright © 2016 Branch Metrics. All rights reserved. // // TODO: rearrange Branch Link section layout // TODO: fix wording when latestRereferringParams are shown import UIKit fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } class HomeViewController: UITableViewController, BranchShareLinkDelegate { @IBOutlet weak var actionButton: UIBarButtonItem! @IBOutlet weak var userIDTextField: UITextField! @IBOutlet weak var linkTextField: UITextField! @IBOutlet weak var createBranchLinkButton: UIButton! @IBOutlet weak var shareBranchLinkButton: UIButton! @IBOutlet weak var linkPropertiesLabel: UILabel! @IBOutlet weak var branchUniversalObjectLabel: UILabel! @IBOutlet weak var ApplicationEventsLabel: UILabel! @IBOutlet weak var CommerceEventLabel: UILabel! @IBOutlet weak var ReferralRewardsLabel: UILabel! @IBOutlet weak var LatestReferringParamsLabel: UILabel! @IBOutlet weak var FirstReferringParamsLabel: UILabel! @IBOutlet weak var TestBedStartupOptionsLabel: UILabel! @IBOutlet weak var ThirdpartySDKIntegrationsLabel: UILabel! var _dateFormatter: DateFormatter? var customEventMetadata = [String: AnyObject]() var commerceEventCustomMetadata = [String: AnyObject]() let shareText = "Shared from Branch's TestBed-Swift" override func viewDidLoad() { super.viewDidLoad() UITableViewCell.appearance().backgroundColor = UIColor.white linkTextField.text = "" refreshControlValues() // Add version to footer let footerView = UILabel.init(frame: CGRect.zero); let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] footerView.text = String(format:"iOS %@ / v%@ / SDK v%@", UIDevice.current.systemVersion, appVersion as! CVarArg, BNC_SDK_VERSION ) footerView.font = UIFont.systemFont(ofSize:11.0) footerView.textAlignment = NSTextAlignment.center footerView.textColor = UIColor.darkGray footerView.sizeToFit() var box = footerView.bounds box.size.height += 10.0 footerView.frame = box self.tableView.tableFooterView = footerView; } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.refreshControlValues() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch((indexPath as NSIndexPath).section, (indexPath as NSIndexPath).row) { case (0,0) : self.performSegue(withIdentifier: "TextViewForm", sender: "UserID") case (1,0) : guard linkTextField.text?.count > 0 else { break } UIPasteboard.general.string = linkTextField.text showAlert("Link copied to clipboard", withDescription: linkTextField.text!) case (1,3) : self.performSegue(withIdentifier: "LinkProperties", sender: "LinkProperties") case (1,4) : self.performSegue(withIdentifier: "BranchUniversalObject", sender: "BranchUniversalObject") case (2,0) : self.performSegue(withIdentifier: "CustomEvent", sender: "CustomEvents") case (2,1) : self.performSegue(withIdentifier: "CommerceEvent", sender: "CommerceEvent") case (2,2) : self.performSegue(withIdentifier: "ReferralRewards", sender: "ReferralRewards") case (3,0) : if let params = Branch.getInstance().getLatestReferringParams() { let content = String(format:"LatestReferringParams:\n\n%@", (params.JSONDescription())) self.performSegue(withIdentifier: "Content", sender: "LatestReferringParams") print("Branch TestBed: LatestReferringParams:\n", content) } case (3,1) : if let params = Branch.getInstance().getFirstReferringParams() { let content = String(format:"FirstReferringParams:\n\n%@", (params.JSONDescription())) self.performSegue(withIdentifier: "Content", sender: "FirstReferringParams") print("Branch TestBed: FirstReferringParams:\n", content) } case (4,0) : self.performSegue(withIdentifier: "TableFormView", sender: "StartupOptions") case (4,1) : self.performSegue(withIdentifier: "IntegratedSDKs", sender: "IntegratedSDKs") default : break } } func dateFormatter() -> DateFormatter { if _dateFormatter != nil { return _dateFormatter!; } _dateFormatter = DateFormatter() _dateFormatter?.locale = Locale(identifier: "en_US_POSIX"); _dateFormatter?.dateFormat = "yyyy-MM-dd'T'HH:mm:ssX" _dateFormatter?.timeZone = TimeZone(secondsFromGMT: 0) return _dateFormatter! } //MARK: - Share a Branch Universal Object with BranchShareLink @IBAction func shareBranchLinkAction(_ sender: AnyObject) { let canonicalIdentifier = "id-" + self.dateFormatter().string(from: Date.init()) let shareBranchObject = BranchUniversalObject.init(canonicalIdentifier: canonicalIdentifier) shareBranchObject.title = "Share Branch Link Example" shareBranchObject.canonicalUrl = "https://developer.branch.io/" shareBranchObject.imageUrl = "https://branch.io/img/press/kit/badge-black.png" shareBranchObject.keywords = [ "example", "short", "share", "link" ] shareBranchObject.contentDescription = "This is an example shared short link." shareBranchObject.contentMetadata.customMetadata["publicSlug"] = canonicalIdentifier; let shareLinkProperties = BranchLinkProperties() shareLinkProperties.controlParams = ["$fallback_url": "https://support.branch.io/support/home"] let branchShareLink = BranchShareLink.init( universalObject: shareBranchObject, linkProperties: shareLinkProperties ) branchShareLink.title = "Share your test link!" branchShareLink.shareText = "Shared from Branch's TestBed-Swift at \(self.dateFormatter().string(from: Date()))" branchShareLink.presentActivityViewController( from: self, anchor: actionButton ) } //MARK: - Link Properties @IBAction func createBranchLinkButtonTouchUpInside(_ sender: AnyObject) { let branchLinkProperties = LinkPropertiesData.branchLinkProperties() let branchUniversalObject = BranchUniversalObjectData.branchUniversalObject() branchUniversalObject.getShortUrl(with: branchLinkProperties) { (url, error) in if (url != nil) { print(branchLinkProperties.description()) print(branchUniversalObject.description()) print("Link Created: \(String(describing: url?.description))") self.linkTextField.text = url } else { print(String(format: "Branch TestBed: %@", error! as CVarArg)) self.showAlert("Link Creation Failed", withDescription: error!.localizedDescription) } } } func textFieldDidChange(_ sender:UITextField) { sender.resignFirstResponder() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { linkTextField.text = "" if let senderName = sender as? String { switch senderName { case "UserID": let nc = segue.destination as! UINavigationController let vc = nc.topViewController as! TextViewFormTableViewController vc.senderName = sender as! String vc.viewTitle = "User ID" vc.header = "User ID" vc.footer = "This User ID (or developer_id) is the application-assigned ID of the user. If not assigned, referrals from links created by the user will show up as 'Anonymous' in reporting." vc.keyboardType = UIKeyboardType.alphabet vc.incumbantValue = userIDTextField.text! case "LinkProperties": let vc = (segue.destination as! LinkPropertiesTableViewController) vc.linkProperties = LinkPropertiesData.linkProperties() case "BranchUniversalObject": let nc = segue.destination as! UINavigationController let vc = nc.topViewController as! BranchUniversalObjectTableViewController vc.universalObject = BranchUniversalObjectData.universalObject() case "CustomEvent": let nc = segue.destination as! UINavigationController let _ = nc.topViewController as! CustomEventTableViewController case "CommerceEvent": let nc = segue.destination as! UINavigationController let _ = nc.topViewController as! CommerceEventTableViewController case "ReferralRewards": let nc = segue.destination as! UINavigationController let _ = nc.topViewController as! ReferralRewardsTableViewController case "LatestReferringParams": let vc = (segue.destination as! ContentViewController) let dict: Dictionary = Branch.getInstance().getLatestReferringParams() if dict["~referring_link"] != nil { vc.contentType = "LatestReferringParams" } else { vc.contentType = "\nNot a referred session" } case "FirstReferringParams": let vc = (segue.destination as! ContentViewController) let dict: Dictionary = Branch.getInstance().getFirstReferringParams() if dict.count > 0 { vc.contentType = "FirstReferringParams" } else { vc.contentType = "\nApp has not yet been opened via a Branch link" } case "StartupOptions": let nc = segue.destination as! UINavigationController let vc = nc.topViewController as! TableFormViewController vc.senderName = sender as! String vc.viewTitle = "Startup Options" vc.keyboardType = UIKeyboardType.alphabet let tableViewSections = [[ "Header":"Active Startup Options", "Footer":"These are the startup options that the application is currently using.", "TableViewCells":[ [ "Name":"ActiveBranchKey", "CellReuseIdentifier":"TextFieldCell", "Text":StartupOptionsData.getActiveBranchKey() ?? "", "Placeholder":"Branch Key" ],[ "Name":"ActiveSetDebugEnabled", "CellReuseIdentifier":"ToggleSwitchCell", "Label":"setDebug Enabled", "isEnabled":"false", "isOn": StartupOptionsData.getActiveSetDebugEnabled()!.description as String ] ] ],[ "Header":"Pending Startup Options", "Footer":"These are the startup options that will be aplied when the app is next launched.", "TableViewCells":[ [ "Name":"PendingBranchKey", "CellReuseIdentifier":"TextFieldCell", "Text":StartupOptionsData.getPendingBranchKey() ?? "", "Placeholder":"Branch Key", "AccessibilityHint":"The Branch key that will be used to initialize this app the next time it is closed (not merely backgrounded) and re-opened.", "InputForm":"TextViewForm" ],[ "Name":"PendingSetDebugEnabled", "CellReuseIdentifier":"ToggleSwitchCell", "Label":"setDebug Enabled", "isEnabled":"true", "isOn":StartupOptionsData.getPendingSetDebugEnabled()!.description as String ] ] ]] vc.tableViewSections = tableViewSections default: break } } } @IBAction func unwindTextViewForm(_ segue:UIStoryboardSegue) { if let vc = segue.source as? TextViewFormTableViewController { switch vc.senderName { case "UserID": if let userID = vc.textView.text { guard self.userIDTextField.text != userID else { return } let branch = Branch.getInstance() guard userID != "" else { branch?.logout { (changed, error) in if (error != nil || !changed) { print(String(format: "Branch TestBed: Unable to clear User ID: %@", error! as CVarArg)) self.showAlert("Error simulating logout", withDescription: error!.localizedDescription) } else { print("Branch TestBed: User ID cleared") self.userIDTextField.text = userID HomeData.setUserID(userID) // Amplitude if IntegratedSDKsData.activeAmplitudeEnabled()! { Amplitude.instance().setUserId(userID) branch?.setRequestMetadataKey("$amplitude_user_id", value: userID) } // Mixpanel if IntegratedSDKsData.activeMixpanelEnabled()! { Mixpanel.sharedInstance()?.identify(userID) branch?.setRequestMetadataKey("$mixpanel_distinct_id", value: userID) } } } return } branch?.setIdentity(userID) { (params, error) in if (error == nil) { print(String(format: "Branch TestBed: Identity set: %@", userID)) self.userIDTextField.text = userID HomeData.setUserID(userID) // Amplitude if IntegratedSDKsData.activeMixpanelEnabled()! { Amplitude.instance().setUserId(userID) branch?.setRequestMetadataKey("$amplitude_user_id", value: userID) } // Mixpanel if IntegratedSDKsData.activeMixpanelEnabled()! { Mixpanel.sharedInstance()?.identify(userID) branch?.setRequestMetadataKey("$mixpanel_distinct_id", value: userID) } } else { print(String(format: "Branch TestBed: Error setting identity: %@", error! as CVarArg)) self.showAlert("Unable to Set Identity", withDescription:error!.localizedDescription) } } } default: break } } } //MARK: - Unwinds @IBAction func unwindByBeingDone(_ segue:UIStoryboardSegue) { // Unwind for closing without cancelling or saving } @IBAction func unwindByCancelling(_ segue:UIStoryboardSegue) { } @IBAction func unwindLinkProperties(_ segue:UIStoryboardSegue) { if let vc = segue.source as? LinkPropertiesTableViewController { LinkPropertiesData.setLinkProperties(vc.linkProperties) } } @IBAction func unwindBranchUniversalObject(_ segue:UIStoryboardSegue) { if let vc = segue.source as? BranchUniversalObjectTableViewController { BranchUniversalObjectData.setUniversalObject(vc.universalObject) } } @IBAction func unwindStartupOptions(_ segue:UIStoryboardSegue) { } @IBAction func unwindIntegratedSDKs(_ segue:UIStoryboardSegue) { print("unwindIntegratedSDKs!") } @IBAction func unwindTableFormView(_ segue:UIStoryboardSegue) { if let vc = segue.source as? TableFormViewController { if let pendingBranchKey = vc.returnValues["PendingBranchKey"] { StartupOptionsData.setPendingBranchKey(pendingBranchKey) } if let pendingSetDebugEnabled = vc.returnValues["PendingSetDebugEnabled"] { StartupOptionsData.setPendingSetDebugEnabled(pendingSetDebugEnabled == "true") } } } func refreshControlValues() { userIDTextField.text = HomeData.userID() } func showAlert(_ alertTitle: String, withDescription message: String) { let alert = UIAlertController(title: alertTitle, message: message, preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel) { UIAlertAction in } alert.addAction(okAction) present(alert, animated: true, completion: nil) } @IBAction func sendPurchaseEvent(_ sender: AnyObject) { let universalObject = BranchUniversalObject.init() universalObject.title = "Big Bad Dog" universalObject.contentDescription = "This dog is big. And bad. Bad dog." universalObject.keywords = [ "big", "bad", "dog" ] universalObject.contentMetadata.contentSchema = BranchContentSchema.commerceProduct universalObject.contentMetadata.price = 10.00 universalObject.contentMetadata.currency = BNCCurrency.USD universalObject.contentMetadata.condition = BranchCondition.poor let event = BranchEvent.standardEvent( BranchStandardEvent.viewItem, withContentItem: universalObject ) event.revenue = 10.00; event.currency = BNCCurrency.USD event.contentItems = [ universalObject ] event.customData = [ "DiggityDog": "Hot" ] event.customData["snoop"] = "dog" BranchEvent.standardEvent(BranchStandardEvent.purchase, withContentItem: universalObject).logEvent() } // Sharing examples @IBAction func shareAliasBranchLinkAction(_ sender: AnyObject) { // Share an alias Branch link: let alias = "Share-Alias-Link-Example" let canonicalIdentifier = alias let shareBranchObject = BranchUniversalObject.init(canonicalIdentifier: canonicalIdentifier) shareBranchObject.title = "Share Branch Link Example" shareBranchObject.canonicalUrl = "https://developer.branch.io/" shareBranchObject.imageUrl = "https://branch.io/img/press/kit/badge-black.png" shareBranchObject.keywords = [ "example", "short", "share", "link" ] shareBranchObject.contentDescription = "This is an example shared alias link." shareBranchObject.contentMetadata.customMetadata["publicSlug"] = canonicalIdentifier let shareLinkProperties = BranchLinkProperties() shareLinkProperties.alias = alias shareLinkProperties.controlParams = ["$fallback_url": "https://support.branch.io/support/home"] let branchShareLink = BranchShareLink.init( universalObject: shareBranchObject, linkProperties: shareLinkProperties ) branchShareLink.title = "Share your alias link!" branchShareLink.delegate = self branchShareLink.shareText = "Shared from Branch's TestBed-Swift at \(self.dateFormatter().string(from: Date()))" branchShareLink.presentActivityViewController( from: self, anchor: actionButton ) } @IBAction func shareAliasActivityViewController(_ sender: AnyObject) { // Share an alias Branch link: let alias = "Share-Alias-Link-Example" let canonicalIdentifier = alias let shareBranchObject = BranchUniversalObject.init(canonicalIdentifier: canonicalIdentifier) shareBranchObject.title = "Share Branch Link Example" shareBranchObject.canonicalIdentifier = "Share-Link-Example-ID" shareBranchObject.canonicalUrl = "https://developer.branch.io/" shareBranchObject.imageUrl = "https://branch.io/img/press/kit/badge-black.png" shareBranchObject.keywords = [ "example", "short", "share", "link" ] shareBranchObject.contentDescription = "This is an example shared alias link." let shareLinkProperties = BranchLinkProperties() shareLinkProperties.alias = alias shareLinkProperties.controlParams = ["$fallback_url": "https://support.branch.io/support/home"] let branchShareLink = BranchShareLink.init( universalObject: shareBranchObject, linkProperties: shareLinkProperties ) branchShareLink.shareText = "Shared with TestBed-Swift" branchShareLink.delegate = self let activityViewController = UIActivityViewController.init( activityItems: branchShareLink.activityItems(), applicationActivities: nil ) self.present(activityViewController, animated: true, completion: nil) } func branchShareLinkWillShare(_ shareLink: BranchShareLink) { // Link properties, such as alias or channel can be overridden here based on the users' // choice stored in shareSheet.activityType. shareLink.shareText = "Shared through '\(shareLink.linkProperties.channel!)'\nfrom Branch's TestBed-Swift" + "\nat \(self.dateFormatter().string(from: Date()))." // In this example, we over-ride the channel so that the channel in the Branch short link // is always 'ios-share'. This allows a short alias link to always be created. shareLink.linkProperties.channel = "ios-share" } func branchShareLink(_ shareLink: BranchShareLink, didComplete completed: Bool, withError error: Error?) { if (error != nil) { print("Branch: Error while sharing! Error: \(error!.localizedDescription).") } else if (completed) { if let channel = shareLink.activityType { print("Branch: User completed sharing with activity '\(channel)'.") Branch.getInstance().userCompletedAction("UserShared", withState: ["Channel": channel]) } } else { print("Branch: User cancelled sharing.") } } }
mit
7d7f639e6b4b40c581df566597b0f69a
45.074906
204
0.574907
5.953061
false
false
false
false
RobinFalko/Ubergang
Ubergang/Ease/Expo.swift
1
1604
// // Expo.swift // Ubergang // // Created by Robin Frielingsdorf on 07/01/16. // Copyright © 2016 Robin Falko. All rights reserved. // import Foundation open class Expo: Easing, CurveEasing { /** Expo ease in. - Parameter t: The value to be mapped going from 0 to `d` - Parameter b: The mapped start value - Parameter c: The mapped end value - Parameter d: The end value - Returns: The mapped result */ open class func easeIn(t: Double, b: Double, c: Double, d: Double) -> Double { return (t==0) ? b : c * pow(2, 10 * (t/d - 1)) + b } /** Circ ease out. - Parameter t: The value to be mapped going from 0 to `d` - Parameter b: The mapped start value - Parameter c: The mapped end value - Parameter d: The end value - Returns: The mapped result */ open class func easeOut(t: Double, b: Double, c: Double, d: Double) -> Double { return (t==d) ? b+c : c * (-pow(2, -10 * t/d) + 1) + b } /** Circ ease in out. - Parameter t: The value to be mapped going from 0 to `d` - Parameter b: The mapped start value - Parameter c: The mapped end value - Parameter d: The end value - Returns: The mapped result */ open class func easeInOut(t: Double, b: Double, c: Double, d: Double) -> Double { var t = t if (t==0) { return b } if (t==d) { return b+c } t/=d/2 if ((t) < 1) { return c/2 * pow(2, 10 * (t - 1)) + b } t-=1 return c/2 * (-pow(2, -10 * t) + 2) + b } }
apache-2.0
061a20792957f3203d56f7da630b4be7
27.122807
85
0.540861
3.410638
false
false
false
false
rgravina/tddtris
TddTetris/Application/AppDelegate.swift
1
1333
import UIKit class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let view = SpriteKitGameView() let gameState = GameState() let collisionDetector = DefaultCollisionDetector( state: gameState ) let tickHandler = DefaultTickHandler( timeKeeper: DefaultTimeKeeper(), actionSelector: DefaultActionSelector( view: view, state: gameState, tetrominoGenerator: DefaultTetrominoGenerator(), collisionDetector: collisionDetector ), gameState: gameState ) let gameVC = GameViewController( launcher: GameLauncher( view: view, tickHandler: tickHandler, inputHandler: DefaultInputHandler( view: view, gameState: gameState, collisionDetector: collisionDetector ) ) ) window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = gameVC window?.makeKeyAndVisible() return true } }
mit
4a639f8754bace1e06c3d5666953e150
30
144
0.581395
6.665
false
false
false
false
stevehe-campray/BSBDJ
BSBDJ/BSBDJ/FriendTrends(关注)/Controllers/BSBrecomendViewController.swift
1
6319
// // BSBrecomendViewController.swift // BSBDJ // // Created by hejingjin on 16/3/16. // Copyright © 2016年 baisibudejie. All rights reserved. // import UIKit class BSBrecomendViewController: UIViewController ,UITableViewDataSource,UITableViewDelegate{ @IBOutlet weak var usertableview: UITableView! @IBOutlet weak var categorytableview: UITableView! private var categoryarray : NSArray = [] private var userarray : [BSBRecommendUser] = [] private var categoryid :NSInteger = 0 private var nextpage :NSInteger = 1 private var totalpage : NSInteger = 1 override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(red: 229/255.0, green: 229/255.0, blue: 229/255.0, alpha: 1.0) setUpMainInterface() loadcategoryData() categorytableview!.registerNib(UINib(nibName: "BSBFriendTrendsCategoryCell", bundle:nil), forCellReuseIdentifier: "category") usertableview!.registerNib(UINib(nibName: "BSBRecommendUserCell", bundle: nil), forCellReuseIdentifier: "RecommendUser") // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func setUpMainInterface(){ self.navigationItem.title = "推荐关注" self.usertableview.showsVerticalScrollIndicator = false self.usertableview.mj_header = MJRefreshNormalHeader(refreshingBlock: { () -> Void in self.loadusersData() }) self.usertableview.mj_footer = MJRefreshBackNormalFooter(refreshingBlock: { () -> Void in if self.nextpage <= self.totalpage{ self.loadMoreUsersData() }else{ self.usertableview.mj_footer.endRefreshing() } }) } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if tableView == categorytableview{ return 44.0 }else{ return 50.0 } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if tableView == categorytableview{ let category : BSBCategory = (self.categoryarray.objectAtIndex(indexPath.row) as? BSBCategory)! self.nextpage = 0 self.categoryid = category.id self.usertableview.mj_header.beginRefreshing() } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == categorytableview { return categoryarray.count }else{ return userarray.count } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if(tableView == categorytableview){ let cell = BSBFriendTrendsCategoryCell.cellWithTableView(tableView) cell.category = self.categoryarray.objectAtIndex(indexPath.row) as? BSBCategory return cell }else{ let cell = BSBRecommendUserCell.cellWithTableview(tableView) let recommenduser : BSBRecommendUser = (userarray[indexPath.row] as? BSBRecommendUser)! cell.recommenduser = recommenduser return cell } } func loadcategoryData(){ let manager = AFHTTPSessionManager() manager.requestSerializer.timeoutInterval = 20.0 let parameter = NSMutableDictionary() parameter.setValue("category", forKey: "a") parameter.setValue("subscribe", forKey: "c") manager.GET(XMGMainURL, parameters: parameter, success: { (_, Json) -> Void in let models:[BSBCategory] = BSBCategory.dict2Model(Json!["list"] as! [[String:AnyObject]]) self.categoryarray = models self.categorytableview.reloadData() self.categorytableview.selectRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), animated: true, scrollPosition: UITableViewScrollPosition.Top) self.categoryid = models[0].id self.usertableview.mj_header.beginRefreshing() }) { (_, error) -> Void in print(error) } } func loadusersData(){ let manager = AFHTTPSessionManager() manager.requestSerializer.timeoutInterval = 20.0 let parameter = NSMutableDictionary() parameter.setValue("list", forKey: "a") parameter.setValue("subscribe", forKey: "c") parameter.setValue(categoryid, forKey: "category_id") manager.GET(XMGMainURL, parameters: parameter, success: { (_, JSON) -> Void in print(JSON) let models:[BSBRecommendUser] = BSBRecommendUser.dict2Model(JSON!["list"] as! [[String:AnyObject]]) self.userarray = models // var nextpagestr:String = as! String self.nextpage = JSON!["next_page"] as! NSInteger self.totalpage = JSON!["total_page"] as! NSInteger self.usertableview.reloadData() self.usertableview.mj_header.endRefreshing() }) { (_, error) -> Void in self.usertableview.mj_header.endRefreshing() print(error) } } func loadMoreUsersData(){ let manager = AFHTTPSessionManager() manager.requestSerializer.timeoutInterval = 20.0 let parameter = NSMutableDictionary() parameter.setValue("list", forKey: "a") parameter.setValue("subscribe", forKey: "c") parameter.setValue(categoryid, forKey: "category_id") parameter.setValue(nextpage, forKey: "page") manager.GET(XMGMainURL, parameters: parameter, success: { (_, JSON) -> Void in let models:[BSBRecommendUser] = BSBRecommendUser.dict2Model(JSON!["list"] as! [[String:AnyObject]]) for model in models{ self.userarray.append(model) } self.usertableview.reloadData() self.usertableview.mj_footer.endRefreshing() }) { (_, error) -> Void in self.usertableview.mj_footer.endRefreshing() } } }
mit
6c88379fe4312c7b2d5906b69b0058e6
38.425
156
0.626506
5.034318
false
false
false
false
kylef/URITemplate.swift
Tests/URITemplateTests/URITemplateExtractTests.swift
1
1244
import Spectre import URITemplate let testExtract: ((ContextType) -> Void) = { $0.it("can extract a basic variable") { let template = URITemplate(template: "{variable}") let values = template.extract("value") try expect(values) == ["variable": "value"] } $0.it("handles composite values") { let template = URITemplate(template: "https://api.github.com/repos/{owner}/{repo}/") try expect(template.extract("https://api.github.com/repos/kylef/PathKit/")) == ["owner":"kylef", "repo":"PathKit"] } $0.it("matches without variables") { let template = URITemplate(template:"https://api.github.com/repos/kylef/URITemplate") try expect(template.extract("https://api.github.com/repos/kylef/URITemplate")?.count) == 0 } $0.it("doesn't match with different URL without variables") { let template = URITemplate(template:"https://api.github.com/repos/kylef/URITemplate") try expect(template.extract("https://api.github.com/repos/kylef/PatkKit")).to.beNil() } $0.it("doesn't match with different URL with variables") { let template = URITemplate(template:"https://api.github.com/repos/{owner}") try expect(template.extract("https://api.github.com/repos/kylef/WebLinking")).to.beNil() } }
mit
8fee53c32dedfe9323d76bd1e07bc28c
37.875
118
0.687299
3.724551
false
false
false
false
SaberVicky/LoveStory
LoveStory/Feature/Publish/LSVideoPlayerViewController.swift
1
1435
// // LSVideoPlayerViewController.swift // LoveStory // // Created by songlong on 2017/1/12. // Copyright © 2017年 com.Saber. All rights reserved. // import UIKit import AVFoundation class LSVideoPlayerViewController: UIViewController { var playerItem:AVPlayerItem! var avplayer:AVPlayer! var playerLayer:AVPlayerLayer! var videoUrl: String! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white let playerView = ZZPlayerView(frame: UIScreen.main.bounds) view.addSubview(playerView) // Do any additional setup after loading the view. let url = URL(string: videoUrl) playerItem = AVPlayerItem(url: url!) avplayer = AVPlayer(playerItem: playerItem) playerLayer = AVPlayerLayer(player: avplayer) playerLayer.videoGravity = AVLayerVideoGravityResizeAspect playerLayer.contentsScale = UIScreen.main.scale playerView.playerLayer = playerLayer playerView.layer.insertSublayer(playerLayer, at: 0) avplayer.play() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { dismiss(animated: true, completion: nil) } } class ZZPlayerView: UIView { var playerLayer:AVPlayerLayer? override func layoutSubviews() { super.layoutSubviews() playerLayer?.frame = bounds } }
mit
be79bf8fd26671eb71f5a568d7be4fb1
26.538462
79
0.668994
4.937931
false
false
false
false
xplorld/WordOuroboros
WordOuroboros/WordCorpus.swift
1
7960
// // WordCorpus.swift // WordOuroboros // // Created by Xplorld on 2015/6/10. // Copyright (c) 2015年 Xplorld. All rights reserved. // import UIKit class WordType : Equatable { let string:String let detailedString:String? lazy var color:UIColor = { WOColor.getColor() }() init(_ s:String) { string = s detailedString = nil } init(s:String,detailedString:String?) { self.string = s self.detailedString = detailedString } } func ==(lhs:WordType,rhs:WordType) -> Bool { return lhs.string == rhs.string } /** array of WordCorpus like WordCorpus( name:"TOEFL 词汇", path:"toefl.json", sample:"Gothic") */ let Corpora:[WordCorpus] = (JSONObjectFromFile("corpusList.json") as! [[String:AnyObject]]) .map{WordCorpus( name:$0["name"] as! String, path:$0["path"] as! String, sample:WordType($0["sample"] as! String), stringKey:$0["stringKey"] as? String, detailedStringKeys:$0["detailedStringKeys"] as? [String] )} /**a corpus. :IMPORTANT: this class does not hold strong reference of `data`, for the sake of saving memory. User of this class shall hold strong reference for both `WordCorpus` and `WordCorpus.data` */ class WordCorpus { let path:String let name:String let sample:WordType private let stringKey:String? private let detailedStringKeys:[String]? init(name: String,path: String,sample:WordType,stringKey:String?,detailedStringKeys:[String]?) { self.name = name self.path = path self.sample = sample self.stringKey = stringKey self.detailedStringKeys = detailedStringKeys } /**`lazy weak` data object*/ var data:WordCorpusData { if (_data == nil) { // println("start processing json") // let time = CFAbsoluteTimeGetCurrent() let data = WordCorpusData() if stringKey == nil { let json = JSONObjectFromFile(self.path) as! NSArray var words:[WordType] = [] for wordLit in json { words.append(WordType(wordLit as! String)) } data.words = words } else { let json = JSONObjectFromFile(self.path) as! NSArray var words:[WordType] = [] for wordDict in json { let theDict = wordDict as! NSDictionary let string = theDict[self.stringKey!] as! String let detail: String if let keys = self.detailedStringKeys { //" ".join(strings) is extremely slow detail = keys.map{theDict[$0] as? String ?? ""}.reduce("", combine: {$0+" "+$1}) } else { detail = "" } words.append(WordType( s: string, detailedString:detail)) } data.words = words } // println("done.\ntime \(CFAbsoluteTimeGetCurrent() - time)") _data = data return data } return _data! } private weak var _data:WordCorpusData? } class WordCorpusData { typealias CharacterType = Character var usedWords:[WordType] = [] ///[Character:[String]] var words:[WordType] = [] { didSet { headMap.removeAll(keepCapacity: false) tailMap.removeAll(keepCapacity: false) for word in words { addWord(word) } } } private func addWord(word:WordType) { if let head = first(word.string) { if headMap[head] == nil { headMap[head] = [] } headMap[head]!.append(word) } if let tail = last(word.string) { if tailMap[tail] == nil { tailMap[tail] = [] } tailMap[tail]!.append(word) } } var headMap:[CharacterType:[WordType]] = [:] var tailMap:[CharacterType:[WordType]] = [:] //TODO: change history from list to graph (like git?) var wordHistory:[WordType] = [] deinit { println("deinit data like \(words.first?.string)") } } //word providing methods //interface extension WordCorpusData { private func wordOfRelationshipToWord(old:WordType,relation:WordRelationship) -> WordType? { if isEmpty(old.string) { return nil } let (oldPicker,newPicker) = charPosition(relation) if let oldChar = oldPicker(old), new = (newPicker(oldChar).filter{[weak self] in !contains(self!.usedWords, $0)}.first) { usedWords.append(new) return new } return nil } func wordBeforeWord(old:WordType) -> WordType? { if let theWord = wordOfRelationshipToWord(old, relation: .Before) { if let index = find(wordHistory, old) { //"ab" with ["eg","gb","bc","cf"] becomes ["ab","bc","cf"] wordHistory.removeRange(0..<index) wordHistory.insert(theWord, atIndex: 0) } else { wordHistory = [theWord,old] } return theWord } return nil } func wordNextToWord(old:WordType) -> WordType? { if let theWord = wordOfRelationshipToWord(old, relation: .After) { if let index = find(wordHistory, old) { wordHistory.removeRange((index+1)..<wordHistory.endIndex) wordHistory.append(theWord) } else { wordHistory = [old,theWord] } return theWord } return nil } func wordBesidesWord(old:WordType) -> WordType? { if let theWord = wordOfRelationshipToWord(old, relation: .Besides) { if let index = find(wordHistory, old) { wordHistory.removeRange(index..<wordHistory.endIndex) wordHistory.append(theWord) } else { wordHistory = [theWord] } return theWord } return nil } func wordFromLiteral(string:String) -> WordType? { if let word = (words.filter{$0.string == string}).first { if !contains(wordHistory, word) { wordHistory = [word] } return word } let word = WordType(string) addWord(word) wordHistory = [word] return word } func randomWord() -> WordType? { if headMap.isEmpty { return nil } let i = Int(arc4random_uniform(UInt32(headMap.count))) let key = Array(headMap.keys)[i] let strs = headMap[key]! let j = Int(arc4random_uniform(UInt32(strs.count))) let word = strs[j] wordHistory = [word] usedWords.append(word) return word } private func charPosition(relationship:WordRelationship) -> (old:(WordType)->CharacterType?,new:(CharacterType)->[WordType]) { let firstChar:(WordType)->CharacterType? = {first($0.string)} let lastChar:(WordType)->CharacterType? = {last($0.string)} let lastSelector:(CharacterType)->[WordType] = {[weak self] in self!.tailMap[$0] ?? []} let firstSelector:(CharacterType)->[WordType] = {[weak self] in self!.headMap[$0] ?? []} switch relationship { case .Before: return (firstChar,lastSelector) case .After: return (lastChar,firstSelector) case .Besides: return (firstChar,firstSelector) case .Irrelevant: fatalError("hehe") } } } enum WordRelationship { case Before case After case Besides case Irrelevant }
mit
eb791ceb216914b16249f1120003eac2
29.592308
130
0.541363
4.537365
false
false
false
false
SoCM/iOS-FastTrack-2014-2015
04-App Architecture/Swift 2/Breadcrumbs/Breadcrumbs-2/Breadcrumbs/ViewController.swift
1
1647
// // ViewController.swift // Breadcrumbs // // Created by Nicholas Outram on 20/01/2016. // Copyright © 2016 Plymouth University. All rights reserved. // import UIKit import MapKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var mapView: MKMapView! lazy var locationManager : CLLocationManager = { let loc = CLLocationManager() //Set up location manager with defaults loc.desiredAccuracy = kCLLocationAccuracyBest loc.distanceFilter = kCLDistanceFilterNone loc.delegate = self //Optimisation of battery loc.pausesLocationUpdatesAutomatically = true loc.activityType = CLActivityType.Fitness loc.allowsBackgroundLocationUpdates = false return loc }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. locationManager.requestAlwaysAuthorization() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - CLLocationManagerDelegate func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if status == CLAuthorizationStatus.AuthorizedAlways { mapView.showsUserLocation = true mapView.userTrackingMode = MKUserTrackingMode.Follow } else { print("Permission Refused") } } }
mit
4f67ce8d49858454f3bc6b8067a04133
26.898305
114
0.660996
6.330769
false
false
false
false
tryswift/RxPagination
Tests/PaginationViewModelTests.swift
1
2184
import Foundation import XCTest import APIKit import RxSwift import RxCocoa import RxTest @testable import Pagination class PaginationViewModelTests: XCTestCase { var disposeBag: DisposeBag! var scheduler: TestScheduler! var sessionAdapter: TestSessionAdapter! var viewModel: PaginationViewModel<Repository>! let viewWillAppear = PublishSubject<Void>() let scrollViewDidScroll = PublishSubject<Void>() override func setUp() { disposeBag = DisposeBag() scheduler = TestScheduler(initialClock: 0, resolution: 1, simulateProcessingDelay: false) driveOnScheduler(scheduler) { sessionAdapter = TestSessionAdapter() let session = Session(adapter: sessionAdapter, callbackQueue: .sessionQueue) let request = GitHubAPI.SearchRepositoriesRequest(query: "Swift") viewModel = PaginationViewModel( baseRequest: request, session: session, viewWillAppear: viewWillAppear.asDriver(onErrorDriveWith: .empty()), scrollViewDidReachBottom: scrollViewDidScroll.asDriver(onErrorDriveWith: .empty())) } } func test() { driveOnScheduler(scheduler) { let indicatorViewAnimating = scheduler.createObserver(Bool.self) let elementsCount = scheduler.createObserver(Int.self) let disposables = [ viewModel.indicatorViewAnimating.drive(indicatorViewAnimating), viewModel.elements.map({ $0.count }).drive(elementsCount), ] scheduler.scheduleAt(10) { self.viewWillAppear.onNext() } scheduler.scheduleAt(20) { self.sessionAdapter.return(data: Fixture.SearchRepositories.data) } scheduler.scheduleAt(30) { disposables.forEach { $0.dispose() } } scheduler.start() XCTAssertEqual(indicatorViewAnimating.events, [ next(0, false), next(10, true), next(20, false), ]) XCTAssertEqual(elementsCount.events, [ next(0, 0), next(20, 30), ]) } } }
mit
a06b4abbb442000944bff7c759211a1b
32.6
106
0.626832
5.501259
false
true
false
false
khizkhiz/swift
validation-test/compiler_crashers_fixed/00819-swift-constraints-constraintsystem-opengeneric.swift
1
433
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class B<T where B = b: Boolean).substringWithRange(i<Int return "cd""",") var _ c())) { typealias f = T)) in c == a: Hashable> String { func a(v: a { enum b in c : A, T -> (x) { } } struct S : P> { } } } var a: B? = 1
apache-2.0
8168887bd44b2e63c54419cad7310d47
21.789474
87
0.642032
3.027972
false
true
false
false
ArtSabintsev/Freedom
Sources/FirefoxFocusFreedomActivity.swift
1
3487
// // FirefoxFocusFreedomActivity.swift // Freedom // // Created by Sabintsev, Arthur on 9/13/17. // Copyright © 2017 Arthur Ariel Sabintsev. All rights reserved. // import UIKit final class FirefoxFocusFreedomActivity: UIActivity, FreedomActivating { override class var activityCategory: UIActivity.Category { return .action } override var activityImage: UIImage? { return UIImage(named: "firefox", in: Freedom.bundle, compatibleWith: nil) } override var activityTitle: String? { return "Open in Firefox Focus" } override var activityType: UIActivity.ActivityType? { guard let bundleID = Bundle.main.bundleIdentifier else { Freedom.printDebugMessage("Failed to fetch the bundleID.") return nil } let type = bundleID + "." + String(describing: FirefoxFocusFreedomActivity.self) return UIActivity.ActivityType(rawValue: type) } var activityDeepLink: String? = "firefox-focus://" var activityURL: URL? override func canPerform(withActivityItems activityItems: [Any]) -> Bool { for item in activityItems { guard let deepLinkURLString = activityDeepLink, let deepLinkURL = URL(string: deepLinkURLString), UIApplication.shared.canOpenURL(deepLinkURL) else { return false } guard let url = item as? URL else { continue } guard url.conformToHypertextProtocol() else { Freedom.printDebugMessage("The URL scheme is missing. This happens if a URL does not contain `http://` or `https://`.") return false } Freedom.printDebugMessage("The user has the Firefox Focus Web Browser installed.") return true } return false } override func prepare(withActivityItems activityItems: [Any]) { activityItems.forEach { item in guard let url = item as? URL, url.conformToHypertextProtocol() else { return Freedom.printDebugMessage("The URL scheme is missing. This happens if a URL does not contain `http://` or `https://`.") } activityURL = url return } } override func perform() { guard let activityURL = activityURL else { Freedom.printDebugMessage("activityURL is missing.") return activityDidFinish(false) } guard let deepLink = activityDeepLink, let url = URL(string: deepLink + "open-url?url=" + activityURL.absoluteString) else { return activityDidFinish(false) } if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:]) { [weak self] opened in guard let strongSelf = self else { return } guard opened else { return strongSelf.activityDidFinish(false) } Freedom.printDebugMessage("The user successfully opened the url, \(activityURL.absoluteString), in the Firefox Focus Web Browser.") strongSelf.activityDidFinish(true) } } else { UIApplication.shared.openURL(url) Freedom.printDebugMessage("The user successfully opened the url, \(activityURL.absoluteString), in the Firefox Focus Web Browser.") activityDidFinish(true) } } }
mit
45933a23210c4675afe406d1ba520bde
32.84466
147
0.607573
5.413043
false
false
false
false
bebeeteam/SZMentionsSwift
SZMentionsExample/SZMentionsExample/Classes/SZExampleMentionsTableViewDataManager.swift
1
2959
// // SZExampleMentionsTableViewDataManager.swift // SZMentionsExample // // Created by Steven Zweier on 1/12/16. // Copyright © 2016 Steven Zweier. All rights reserved. // import UIKit import SZMentionsSwift fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } class SZExampleMentionsTableViewDataManager: NSObject, UITableViewDataSource, UITableViewDelegate { fileprivate var listener: SZMentionsListener? fileprivate var mentions: [SZExampleMention] { let names = [ "Steven Zweier", "John Smith", "Joe Tesla"] var tempMentions = [SZExampleMention]() for name in names { let mention = SZExampleMention.init(withName: name) tempMentions.append(mention) } return tempMentions } fileprivate var tableView: UITableView? fileprivate var filterString: String? init(mentionTableView: UITableView, mentionsListener: SZMentionsListener) { tableView = mentionTableView tableView!.register( UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell") listener = mentionsListener } func filter(_ string: String?) { filterString = string tableView?.reloadData() } fileprivate func mentionsList() -> [SZExampleMention] { var filteredMentions = mentions if (filterString?.characters.count > 0) { filteredMentions = mentions.filter() { if let type = ($0 as SZExampleMention).szMentionName as String! { return type.lowercased().contains(filterString!.lowercased()) } else { return false } } } return filteredMentions } func firstMentionObject() -> SZExampleMention? { return mentionsList().first } func addMention(_ mention: SZExampleMention) { listener!.addMention(mention) } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mentionsList().count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") cell?.textLabel?.text = mentionsList()[(indexPath as NSIndexPath).row].szMentionName as String return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { self.addMention(mentionsList()[(indexPath as NSIndexPath).row]) } }
mit
28edb2fa14417c7825bd1b48e0e5b1df
26.64486
102
0.627789
4.809756
false
false
false
false
dcunited001/SpectraNu
Spectra/SpectraXML/XSD.swift
1
2793
// // XSD.swift // // // Created by David Conner on 3/9/16. // // import Foundation import Fuzi import Swinject public class SpectraEnum { let name: String var values: [String: UInt] public init(elem: XMLElement) { values = [:] name = elem.attributes["name"]! let valuesSelector = "xs:restriction > xs:enumeration" for child in elem.css(valuesSelector) { let val = child.attributes["id"]! let key = child.attributes["value"]! self.values[key] = UInt(val) } } public func getValue(id: String) -> UInt { return values[id]! } } // TODO: is there struct value that makes sense here? // - so, like a single struct value that can be used in case statements // - but also carries a bit of info about the params of each type? public enum SpectraVertexAttrType: String { // raw values for enums must be literals, // - so i can't use the MDLVertexAttribute string values case Anisotropy = "anisotropy" case Binormal = "binormal" case Bitangent = "bitangent" case Color = "color" case EdgeCrease = "edgeCrease" case JointIndices = "jointIndices" case JointWeights = "jointWeights" case Normal = "normal" case OcclusionValue = "occlusionValue" case Position = "position" case ShadingBasisU = "shadingBasisU" case ShadingBasisV = "shadingBasisV" case SubdivisionStencil = "subdivisionStencil" case Tangent = "tangent" case TextureCoordinate = "textureCoordinate" // can't add this to the SpectraEnums.xsd schema, // - at least not directly, since it's not an enum } public class SpectraXSD { public class func readXSD(filename: String) -> XMLDocument? { let bundle = NSBundle(forClass: MetalXSD.self) let path = bundle.pathForResource(filename, ofType: "xsd") let data = NSData(contentsOfFile: path!) do { return try XMLDocument(data: data!) } catch let err as XMLError { switch err { case .ParserFailure, .InvalidData: print(err) case .LibXMLError(let code, let message): print("libxml error code: \(code), message: \(message)") default: break } } catch let err { print("error: \(err)") } return nil } public func parseXSD(xsd: XMLDocument, container: Container = Container()) -> Container { let enumTypesSelector = "xs:simpleType[mtl-enum=true]" for enumChild in xsd.css(enumTypesSelector) { let enumType = SpectraEnum(elem: enumChild) container.register(SpectraEnum.self, name: enumType.name) { _ in return enumType } } return container } }
mit
708c9eaabbce36533df181dff009fdbf
29.703297
110
0.619048
4.181138
false
false
false
false
asm-products/giraff-ios
Fun/FaveViewController.swift
1
5850
import UIKit class AsyncFaveViewController : UIViewController, ASCollectionViewDataSource, ASCollectionViewDelegate { @IBOutlet weak var revealButtonItem: UIBarButtonItem! let collectionView: ASCollectionView var deck = Deck(deckSourceMode: .Faves) required init(coder aDecoder: NSCoder) { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .Vertical layout.minimumInteritemSpacing = 0.0; layout.minimumLineSpacing = 0.0; collectionView = ASCollectionView(frame: CGRectZero, collectionViewLayout: layout, asyncDataFetching: false) super.init(coder: aDecoder) collectionView.asyncDataSource = self collectionView.asyncDelegate = self collectionView.backgroundColor = UIColor.blackColor() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated); // GA var tracker = GAI.sharedInstance().defaultTracker tracker.set(kGAIScreenName, value: "Favorites") let event = GAIDictionaryBuilder.createScreenView().build() as NSDictionary tracker.send(event as [NSObject: AnyObject]) } override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(self.collectionView) Flurry.logAllPageViewsForTarget(self.navigationController) Flurry.logEvent("Favorite Page Shown") let titleImage = UIImage(named: "fun-logo.png") let titleImageView = UIImageView(frame: CGRectMake(0, 0, 30, 30)) titleImageView.contentMode = .ScaleAspectFit titleImageView.image = titleImage self.navigationItem.titleView = titleImageView let rvc = self.revealViewController() revealButtonItem.target = rvc revealButtonItem.action = "revealToggle:" navigationController!.navigationBar.addGestureRecognizer(rvc.panGestureRecognizer()) weak var weakSelf = self deck.fetch() { dispatch_async(dispatch_get_main_queue()) { if let strongSelf = weakSelf { strongSelf.collectionView.reloadData() } NSLog("fetched faves") } } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.collectionView.frame = self.view.bounds } func collectionView(collectionView: ASCollectionView!, nodeForItemAtIndexPath indexPath: NSIndexPath!) -> ASCellNode! { //TODO make this safer let card = deck.cardAtIndex(UInt(indexPath.row)) as Card! let faveNode = FaveNode(thumbnailURL:NSURL(string:card.gifUrlPreview!)!) return faveNode } func collectionView(collectionView: UICollectionView!, numberOfItemsInSection section: Int) -> Int { return Int(deck.count()) } func collectionView(collectionView: ASCollectionView!, willBeginBatchFetchWithContext context: ASBatchContext!) { let deckCount = deck.count() deck.fetch { [weak self]() -> Void in if let strongSelf = self { let newDeckCount = strongSelf.deck.count() var indexPaths: Array<NSIndexPath> = [] for index in deckCount ..< newDeckCount { indexPaths.append(NSIndexPath(forRow: Int(index), inSection: 0)) } strongSelf.collectionView.insertItemsAtIndexPaths(indexPaths); } context.completeBatchFetching(true) } } func collectionView(collectionView: UICollectionView!, didSelectItemAtIndexPath indexPath: NSIndexPath!) { self.performSegueWithIdentifier("detail", sender: deck.cardAtIndex(UInt(indexPath!.row))) } func collectionViewLockDataSource(collectionView: ASCollectionView!) { //What to do? } func collectionViewUnlockDataSource(collectionView: ASCollectionView!) { //What to do? } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "detail" { let card = sender as! Card let vc = segue.destinationViewController as! DetailViewController vc.card = card } } } class FaveNode : ASCellNode { let imageNode: ASNetworkImageNode let kCellInnerPadding = CGFloat(5.0) init(thumbnailURL: NSURL) { imageNode = ASNetworkImageNode() super.init() let cornerRadius = CGFloat(10.0) self.backgroundColor = UIColor.blackColor() imageNode.backgroundColor = ASDisplayNodeDefaultPlaceholderColor(); imageNode.cornerRadius = cornerRadius imageNode.URL = thumbnailURL imageNode.contentMode = .ScaleAspectFit imageNode.imageModificationBlock = { [weak self](image: UIImage!) -> UIImage in let rect = CGRect(origin: CGPointZero, size:image.size) UIGraphicsBeginImageContextWithOptions(image.size, false, UIScreen.mainScreen().scale); UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip() image.drawInRect(rect) let modifiedImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage UIGraphicsEndImageContext(); return modifiedImage } self.addSubnode(imageNode) } func calculateSizeThatFits(constrainedSize: CGSize) -> CGSize { let availableWidth = constrainedSize.width / 3.0; return CGSizeMake(availableWidth, availableWidth) } func layout() { imageNode.frame = CGRectMake(kCellInnerPadding, kCellInnerPadding, self.calculatedSize.width - 2.0 * kCellInnerPadding, self.calculatedSize.height - 2.0 * kCellInnerPadding) } }
agpl-3.0
a75543cedde0a05428c62b384259bf8b
37.486842
181
0.653504
5.635838
false
false
false
false
guidomb/Portal
PortalTests/View/UIKit/Renderers/ButtonRendererSpec.swift
1
7097
// // ButtonRendererSpec.swift // Portal // // Created by Guido Marucci Blas on 8/5/17. // Copyright © 2017 Guido Marucci Blas. All rights reserved. // import Quick import Nimble @testable import Portal class ButtonRendererSpec: QuickSpec { override func spec() { var layoutEngine: LayoutEngine! beforeEach { layoutEngine = YogaLayoutEngine() } describe(".apply(changeSet: ButtonChangeSet, layoutEngine: LayoutEngine) -> Result") { var changeSet: ButtonChangeSet<String>! var buttonIcon: Image! beforeEach { Image.unregisterAllImageBundles() Image.registerImageBundle(Bundle(for: ButtonRendererSpec.self)) buttonIcon = .localImage(named: "search.png") let buttonProperties: ButtonProperties<String> = properties { $0.text = "Hello World" $0.isActive = true $0.icon = buttonIcon $0.onTap = "Tapped!" } let buttonStyle = buttonStyleSheet { base, button in button.textColor = .red button.textFont = Font(name: "Helvetica") button.textSize = 12 } changeSet = ButtonChangeSet.fullChangeSet( properties: buttonProperties, style: buttonStyle, layout: layout() ) } context("when the change set contains button property changes") { it("applies 'text' property changes") { let button = UIButton() _ = button.apply(changeSet: changeSet, layoutEngine: layoutEngine) expect(button.currentTitle).to(equal("Hello World")) } it("applies 'isActive' property changes") { let button = UIButton() _ = button.apply(changeSet: changeSet, layoutEngine: layoutEngine) expect(button.isSelected).to(beTrue()) } it("applies 'icon' property changes") { let button = UIButton() _ = button.apply(changeSet: changeSet, layoutEngine: layoutEngine) expect(button.currentImage).toEventually(equal(buttonIcon.asUIImage)) } it("applies 'onTap' property changes") { waitUntil { done in let button = UIButton() let result = button.apply(changeSet: changeSet, layoutEngine: layoutEngine) result.mailbox?.subscribe { message in expect(message).to(equal("Tapped!")) done() } button.sendActions(for: .touchUpInside) }} context("when there are optional properties set to .none") { var configuredButton: UIButton! beforeEach { configuredButton = UIButton() _ = configuredButton.apply(changeSet: changeSet, layoutEngine: layoutEngine) } it("removes the button's title") { let newChangeSet = ButtonChangeSet<String>(properties: [.text(.none)]) _ = configuredButton.apply(changeSet: newChangeSet, layoutEngine: layoutEngine) expect(configuredButton.currentTitle).to(beNil()) } it("removes the button's icon") { let newChangeSet = ButtonChangeSet<String>(properties: [.icon(.none)]) _ = configuredButton.apply(changeSet: newChangeSet, layoutEngine: layoutEngine) expect(configuredButton.currentImage).to(beNil()) } it("removes the button's on tap handler") { let newChangeSet = ButtonChangeSet<String>(properties: [.onTap(.none)]) let result = configuredButton.apply(changeSet: newChangeSet, layoutEngine: layoutEngine) result.mailbox?.subscribe { _ in fail("On tap handler was not removed") } configuredButton.sendActions(for: .touchUpInside) } } context("when an on tap handler is already configured") { var configuredButton: UIButton! beforeEach { configuredButton = UIButton() _ = configuredButton.apply(changeSet: changeSet, layoutEngine: layoutEngine) } it("replaces the previous on tap handler") { let newChangeSet = ButtonChangeSet<String>(properties: [.onTap("NewMessage!")]) let result = configuredButton.apply(changeSet: newChangeSet, layoutEngine: layoutEngine) // We need reference semantics to avoid copies inside mailbox's subscribe // closure in order to assert that the expected messages were received. let receivedMessages = NSMutableArray() result.mailbox?.subscribe { receivedMessages.add($0) } configuredButton.sendActions(for: .touchUpInside) expect(receivedMessages.count).to(equal(1)) expect(receivedMessages.firstObject as? String).to(equal("NewMessage!")) } } } context("when the change set contains button stylesheet changes") { it("applies 'textColor' property changes") { let button = UIButton() _ = button.apply(changeSet: changeSet, layoutEngine: layoutEngine) expect(button.titleLabel?.textColor).to(equal(.red)) } it("applies 'textFont' and 'textSize' property changes") { let button = UIButton() _ = button.apply(changeSet: changeSet, layoutEngine: layoutEngine) expect(button.titleLabel?.font).to(equal(UIFont(name: "Helvetica", size: 12))) } } } } }
mit
9a09a24063a9aba5307d2e89838a6f02
42.268293
112
0.470829
6.71334
false
true
false
false
taqun/HBR
HBR/Classes/Util/FeedURLBuilder.swift
1
2526
// // FeedURLBuilder.swift // HBR // // Created by taqun on 2015/06/23. // Copyright (c) 2015年 envoixapp. All rights reserved. // import UIKit class FeedURLBuilder: NSObject { private static var HATENA_CATEGORY_PATH: [HatenaCategory: String] = [ HatenaCategory.General : "general", HatenaCategory.Social : "social", HatenaCategory.Economics : "economics", HatenaCategory.Life : "life", HatenaCategory.Knowledge : "knowledge", HatenaCategory.It : "it", HatenaCategory.Fun : "fun", HatenaCategory.Entertainment : "entertainment", HatenaCategory.Anime : "game" ] /* * Public Method */ static func buildFeedURL(channel: Channel) -> (String) { switch channel.type { case ChannelType.Hot: return FeedURLBuilder.buildHotEntryFeedURL(channel.category) case ChannelType.New: return FeedURLBuilder.buildNewEntryFeedURL(channel.category) default: return FeedURLBuilder.buildKeywordFeedURL(channel.type, keyword: channel.keyword, bookmarkNum: channel.bookmarkNum) } } /* * Private Method */ private static func buildHotEntryFeedURL(category: HatenaCategory) -> (String) { if category == HatenaCategory.All { return "http://b.hatena.ne.jp/hotentry.rss" } else { let path = HATENA_CATEGORY_PATH[category]! return "http://b.hatena.ne.jp/hotentry/\(path).rss" } } private static func buildNewEntryFeedURL(category: HatenaCategory) -> (String) { if category == HatenaCategory.All { return "http://b.hatena.ne.jp/entrylist?sort=hot&threshold=3&mode=rss" } else { let path = HATENA_CATEGORY_PATH[category]! return "http://b.hatena.ne.jp/entrylist/\(path)?sort=hot&threshold=3&mode=rss" } } private static func buildKeywordFeedURL(type: ChannelType, keyword: String, bookmarkNum: NSNumber) -> (String) { let escapedKeyword = keyword.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! let typeString = type.rawValue return "http://b.hatena.ne.jp/search/\(typeString)?safe=on&q=\(escapedKeyword)&users=\(bookmarkNum)&mode=rss" } }
mit
c02fc0051a9cfd8d31f4c2da04771813
34.055556
134
0.596276
4.589091
false
false
false
false
ihomway/RayWenderlichCourses
iOS Concurrency with GCD and Operations/iOS Concurrency with GCD and Operations.playground/Pages/OperationQueue.xcplaygroundpage/Contents.swift
1
2505
//: [Previous](@previous) import UIKit import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true //: # OperationQueue //: `OperationQueue` is responsible for scheduling and running a set of operations, somewhere in the background. //: ## Creating a queue //: Creating a queue is simple, using the default initializer; you can also set the maximum number of queued operations that can execute at the same time: // TODO: Create printerQueue let printerQueue = OperationQueue() // TODO later: Set maximum to 2 printerQueue.maxConcurrentOperationCount = 2 //: ## Adding `Operations` to Queues /*: `Operation`s can be added to queues directly as closures - important: Adding operations to a queue is really "cheap"; although the operations can start executing as soon as they arrive on the queue, adding them is completely asynchronous. \ You can see that here, with the result of the `duration` function: */ // TODO: Add 5 operations to printerQueue duration { printerQueue.addOperation { print("Hello"); sleep(3) } printerQueue.addOperation { print("my"); sleep(3) } printerQueue.addOperation { print("name"); sleep(3) } printerQueue.addOperation { print("is"); sleep(3) } printerQueue.addOperation { print("Homway"); sleep(3) } } // TODO: Measure duration of all operations duration { printerQueue.waitUntilAllOperationsAreFinished() } //: ## Filtering an Array of Images //: Now for a more real-world example. let images = ["city", "dark_road", "train_day", "train_dusk", "train_night"].map { UIImage(named: "\($0).jpg") } var filteredImages = [UIImage]() //: Create the queue with the default initializer: // TODO: Create filterQueue let filterQueue = OperationQueue() //: Create a serial queue to handle additions to the array: // TODO: Create serial appendQueue let appendQueue = OperationQueue() appendQueue.maxConcurrentOperationCount = 1 //: Create a filter operation for each of the images, adding a `completionBlock`: for image in images { // TODO: as above let filterOp = TiltShiftOperation() filterOp.inputImage = image filterOp.completionBlock = { guard let output = filterOp.outputImage else { return } appendQueue.addOperation { filteredImages.append(output) } } filterQueue.addOperation(filterOp) } //: Need to wait for the queue to finish before checking the results // TODO: wait filterQueue.waitUntilAllOperationsAreFinished() //: Inspect the filtered images filteredImages //PlaygroundPage.current.finishExecution() //: [Next](@next)
mit
807ed9ef1f8c5e5d2e900f78d98b965d
33.791667
168
0.751697
4.245763
false
false
false
false
mityung/XERUNG
IOS/Xerung/Xerung/Register2ViewController.swift
1
11625
// // Register2ViewController.swift // Xerung // // Created by Mac on 30/03/17. // Copyright © 2017 mityung. All rights reserved. // import UIKit class Register2ViewController: UIViewController, UITextFieldDelegate { @IBOutlet var submitButton: UIButton! @IBOutlet var otpText: UITextField! @IBOutlet var emailText: UITextField! @IBOutlet var fullNameText: UITextField! @IBOutlet var view2: UIView! @IBOutlet var view1: UIView! @IBOutlet var fullNameView: UIView! @IBOutlet var otpView: UIView! @IBOutlet var emailView: UIView! @IBOutlet var numberLabel: UILabel! var mobileNumber:String! var otp:String! override func viewDidLoad() { super.viewDidLoad() mobileNumber = mobileNo submitButton.layer.cornerRadius = 5 submitButton.layer.masksToBounds = true submitButton.tintColor = UIColor.white submitButton.backgroundColor = themeColor view1.dropShadow() view2.dropShadow() otpText.delegate = self otpText.keyboardType = .numberPad otpText.tag = 3 emailText.delegate = self emailText.keyboardType = .emailAddress emailText.tag = 2 fullNameText.delegate = self fullNameText.tag = 1 numberLabel.text = mobileNo submitButton.addTarget(self, action: #selector(self.sendOTPtoServer), for: UIControlEvents.touchUpInside) let numberToolbar: UIToolbar = UIToolbar() numberToolbar.barStyle = UIBarStyle.default numberToolbar.items=[ UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: self, action: nil), UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.Apply)) ] numberToolbar.sizeToFit() otpText.inputAccessoryView = numberToolbar } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { var allowedCharacter = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz?.,/ " if textField.tag == 1 { allowedCharacter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz " }else if textField.tag == 2 { allowedCharacter = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz?.@_" }else if textField.tag == 3 { allowedCharacter = "0123456789" }else { allowedCharacter = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz?.,/ " } let aSet = CharacterSet(charactersIn:allowedCharacter).inverted let compSepByCharInSet = string.components(separatedBy: aSet) let numberFiltered = compSepByCharInSet.joined(separator: "") if string == numberFiltered{ let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string) let numberOfChars = newText.characters.count if textField.tag == 1 { return numberOfChars < 31 }else if textField.tag == 2 { return numberOfChars < 50 }else if textField.tag == 3 { return numberOfChars < 6 }else { return numberOfChars < 51 } }else{ return string == numberFiltered } } func textFieldDidBeginEditing(_ textField: UITextField) { if textField.tag == 1 { fullNameView.backgroundColor = themeColor }else if textField.tag == 2 { emailView.backgroundColor = themeColor }else if textField.tag == 3 { otpView.backgroundColor = themeColor } } @available(iOS 10.0, *) func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) { if textField.tag == 1 { fullNameView.backgroundColor = UIColor.lightGray }else if textField.tag == 2 { emailView.backgroundColor = UIColor.lightGray }else if textField.tag == 3 { otpView.backgroundColor = UIColor.lightGray } } func Apply () { self.view.endEditing(true) } @IBAction func editButton(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func backButton(_ sender: AnyObject) { self.dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func sendOTPtoServer(_ sender: AnyObject) { self.Apply() if fullNameText.text?.trim().characters.count == 0 { self.showAlert("Alert", message: "Please fill name.") return } if emailText.text?.trim().characters.count == 0 { self.showAlert("Alert", message: "Please fill email address.") return }else if self.isValidEmail(testStr: emailText.text!) == false { self.showAlert("Alert", message: "Please fill valid email address.") return } if otpText.text?.trim().characters.count == 0 { self.showAlert("Alert", message: "Please fill OTP.") return } if otpText.text! != OTPText { self.showAlert("Alert", message: "OTP is not matched.") return } let sendJson: [String: String] = [ "PPHONENUMBER":(CountryPhoneCode + mobileNumber) , "PEMAIL": emailText.text!, "PNAME":fullNameText.text!.trim(), "PADDRESS": "", "PCITYID":"0", "PSTATEID":"0", "PCOUNTRYCODEID":CountryPhoneCode, "PCOUNTRYNAME":CountryName, "POTPID":otpText.text!, "PSTATUSID":"0", "PPROFESSION":"", "PLOGINFLAG":"0" ] print(sendJson) if Reachability.isConnectedToNetwork() { startLoader(view: self.view) DataProvider.sharedInstance.getServerData(sendJson, path: "RegLogin", successBlock: { (response) in // self.fetchProfile(String(response["UID"].intValue)) print(response) if response["STATUS"].stringValue == "3" { self.showAlert("Alert", message: "Email Address already register.") }else{ userID = String(response["UID"].intValue) self.fetchProfile(userID) } stopLoader() }) { (error) in print(error) stopLoader() } }else{ showAlert("Alert", message: "No internet connectivity.") } } func fetchProfile(_ uid:String) { let sendJson: [String: String] = [ "PUID":uid ] if Reachability.isConnectedToNetwork() { startLoader(view: self.view) DataProvider.sharedInstance.getServerData(sendJson, path: "fetchProfile", successBlock: { (response) in print(response) profileJson = response name = response["NAME"].stringValue mobileNo = response["PHONENUMBER"].stringValue UserDefaults.standard.set(String(describing: profileJson), forKey: "profileJson") // NSUserDefaults.standardUserDefaults().setValue(profileJson, forKey: "profileJson") UserDefaults.standard.setValue(name, forKey: "name") UserDefaults.standard.setValue(mobileNo, forKey: "mobileNo") UserDefaults.standard.setValue(uid, forKey: "uid") UserDefaults.standard.setValue("Yes", forKey: "Login") UserDefaults.standard.setValue(CountryPhoneCode, forKey: "CountryPhoneCode") UserDefaults.standard.setValue(CountryCode, forKey: "CountryCode") UserDefaults.standard.setValue(CountryName, forKey: "CountryName") UserDefaults.standard.synchronize() stopLoader() self.nextView() }) { (error) in print(error) stopLoader() } }else{ showAlert("Alert", message: "No internet connectivity.") } } func isValidEmail(testStr:String) -> Bool { // print("validate calendar: \(testStr)") let emailRegEx = "^(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?(?:(?:(?:[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+(?:\\.[-A-Za-z0-9!#$%&’*+/=?^_'{|}~]+)*)|(?:\"(?:(?:(?:(?: )*(?:(?:[!#-Z^-~]|\\[|\\])|(?:\\\\(?:\\t|[ -~]))))+(?: )*)|(?: )+)\"))(?:@)(?:(?:(?:[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)(?:\\.[A-Za-z0-9](?:[-A-Za-z0-9]{0,61}[A-Za-z0-9])?)*)|(?:\\[(?:(?:(?:(?:(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))\\.){3}(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))))|(?:(?:(?: )*[!-Z^-~])*(?: )*)|(?:[Vv][0-9A-Fa-f]+\\.[-A-Za-z0-9._~!$&'()*+,;=:]+))\\])))(?:(?:(?:(?: )*(?:(?:(?:\\t| )*\\r\\n)?(?:\\t| )+))+(?: )*)|(?: )+)?$" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) let result = emailTest.evaluate(with: testStr) return result } func nextView(){ DispatchQueue.main.async(execute: { let storyBoard = UIStoryboard(name: "Main", bundle: nil) as UIStoryboard let mfSideMenuContainer = storyBoard.instantiateViewController(withIdentifier: "MFSideMenuContainerViewController") as! MFSideMenuContainerViewController let dashboard = storyBoard.instantiateViewController(withIdentifier: "Directory_ViewController") as! UITabBarController let leftSideMenuController = storyBoard.instantiateViewController(withIdentifier: "SideMenuViewController") as! SideMenuViewController mfSideMenuContainer.leftMenuViewController = leftSideMenuController mfSideMenuContainer.centerViewController = dashboard let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.window?.rootViewController = mfSideMenuContainer // self.performSegue(withIdentifier: "register", sender: nil) }) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // show alert using this method func showAlert(_ title:String,message:String){ let refreshAlert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert) refreshAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action: UIAlertAction!) in })) present(refreshAlert, animated: true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
75092d0e444ee3d40705be901bc7a9d2
37.993289
701
0.573666
5.028126
false
false
false
false
hkellaway/Gloss
GlossExample/GlossExample/ViewController.swift
1
3614
// // ViewController.swift // GlossExample // // Copyright (c) 2020 Harlan Kellaway // // 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 Gloss import UIKit extension JSONDecoder { // GitHub API uses snake-case static func snakeCase() -> JSONDecoder { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase return decoder } } extension JSONEncoder { // GitHub API uses snake-case static func snakeCase() -> JSONEncoder { let encoder = JSONEncoder() encoder.keyEncodingStrategy = .convertToSnakeCase return encoder } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let repoJSON: JSON = [ "id" : 40102424, "name": "Gloss", "description" : "A shiny JSON parsing library in Swift", "html_url" : "https://github.com/hkellaway/Gloss", "owner" : [ "id" : 5456481, "login" : "hkellaway", "html_url" : "https://github.com/hkellaway" ], "language" : "Swift" ] let decodedRepo: Repo? = .from(decodableJSON: repoJSON, jsonDecoder: .snakeCase()) guard let repo = decodedRepo else { print("DECODING FAILURE :(") return } print(repo.repoId) print(repo.name) print(repo.desc!) print(repo.urlString!) print(repo.owner) print(repo.primaryLanguage?.rawValue ?? "No language") print("") print("JSON: \(repo.toEncodableJSON(jsonEncoder: .snakeCase())!)") print("") guard let repos = [Repo].from(decodableJSONArray: [repoJSON, repoJSON, repoJSON], jsonDecoder: .snakeCase()) else { print("DECODING FAILURE :(") return } print("REPOS: \(repos)") print("") guard let jsonArray = repos.toEncodableJSONArray(jsonEncoder: .snakeCase()) else { print("ENCODING FAILURE :(") return } print("JSON ARRAY: \(jsonArray)") if let data = GlossJSONSerializer().data(from: repoJSON, options: nil) { do { let repo = try JSONDecoder.snakeCase().decode(Repo.self, from: data) print(repo.name) } catch { print(error.localizedDescription) } } } }
mit
474607cca3559b8443121218d421e382
30.982301
90
0.597122
4.8251
false
false
false
false
novastorm/Udacity-On-The-Map
On the Map/ProgressOverlay.swift
1
1501
// // ProgressOverlay.swift // On the Map // // Created by Adland Lee on 4/9/16. // Copyright © 2016 Adland Lee. All rights reserved. // import UIKit class ProgressOverlay { // MARK: Properties static let sharedInstance = ProgressOverlay() var presentingVC: UIViewController? let alertView = UIAlertController() let activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50)) // MARK: Initializers // This is a Singleton, make initializer private fileprivate init() { alertView.view.tintColor = UIColor.black alertView.view.addSubview(activityIndicator) activityIndicator.activityIndicatorViewStyle = .gray } static func start(_ vc: UIViewController, title: String? = nil, message: String? = nil, completion: (() -> Void)?) { sharedInstance.presentingVC = vc sharedInstance.alertView.view.layoutIfNeeded() sharedInstance.alertView.title = title sharedInstance.alertView.message = message sharedInstance.activityIndicator.startAnimating() sharedInstance.presentingVC!.present(sharedInstance.alertView, animated: true, completion: completion) } static func stop(_ completion: (() -> Void)?) { sharedInstance.activityIndicator.stopAnimating() sharedInstance.alertView.dismiss(animated: true, completion: completion) sharedInstance.presentingVC = nil } }
mit
6c9e51bafa14763612cec072fff78f2e
29.612245
120
0.673333
5.136986
false
false
false
false
Aahung/two-half-password
Pods/SwiftyUserDefaults/Src/SwiftyUserDefaults.swift
4
4831
// // SwiftyUserDefaults // // Copyright (c) 2015 Radosław Pietruszewski // // 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 NSUserDefaults { class Proxy { private let defaults: NSUserDefaults private let key: String private init(_ defaults: NSUserDefaults, _ key: String) { self.defaults = defaults self.key = key } // MARK: Getters public var object: NSObject? { return defaults.objectForKey(key) as? NSObject } public var string: String? { return defaults.stringForKey(key) } public var array: NSArray? { return defaults.arrayForKey(key) } public var dictionary: NSDictionary? { return defaults.dictionaryForKey(key) } public var data: NSData? { return defaults.dataForKey(key) } public var date: NSDate? { return object as? NSDate } public var number: NSNumber? { return object as? NSNumber } public var int: Int? { return number?.integerValue } public var double: Double? { return number?.doubleValue } public var bool: Bool? { return number?.boolValue } } /// Returns getter proxy for `key` public subscript(key: String) -> Proxy { return Proxy(self, key) } /// Sets value for `key` public subscript(key: String) -> Any? { get { return self[key] } set { if let v = newValue as? Int { setInteger(v, forKey: key) } else if let v = newValue as? Double { setDouble(v, forKey: key) } else if let v = newValue as? Bool { setBool(v, forKey: key) } else if let v = newValue as? NSObject { setObject(v, forKey: key) } else if newValue == nil { removeObjectForKey(key) } else { assertionFailure("Invalid value type") } } } /// Returns `true` if `key` exists public func hasKey(key: String) -> Bool { return objectForKey(key) != nil } /// Removes value for `key` public func remove(key: String) { removeObjectForKey(key) } } infix operator ?= { associativity right precedence 90 } /// If key doesn't exist, sets its value to `expr` /// Note: This isn't the same as `Defaults.registerDefaults`. This method saves the new value to disk, whereas `registerDefaults` only modifies the defaults in memory. /// Note: If key already exists, the expression after ?= isn't evaluated public func ?= (proxy: NSUserDefaults.Proxy, @autoclosure expr: () -> Any) { if !proxy.defaults.hasKey(proxy.key) { proxy.defaults[proxy.key] = expr() } } /// Adds `b` to the key (and saves it as an integer) /// If key doesn't exist or isn't a number, sets value to `b` public func += (proxy: NSUserDefaults.Proxy, b: Int) { let a = proxy.defaults[proxy.key].int ?? 0 proxy.defaults[proxy.key] = a + b } public func += (proxy: NSUserDefaults.Proxy, b: Double) { let a = proxy.defaults[proxy.key].double ?? 0 proxy.defaults[proxy.key] = a + b } /// Icrements key by one (and saves it as an integer) /// If key doesn't exist or isn't a number, sets value to 1 public postfix func ++ (proxy: NSUserDefaults.Proxy) { proxy += 1 } /// Global shortcut for NSUserDefaults.standardUserDefaults() public let Defaults = NSUserDefaults.standardUserDefaults()
mit
1f1bc4febd1f1268de2cc7077c66e281
29.377358
167
0.603934
4.591255
false
false
false
false
antonio081014/LeeCode-CodeBase
Swift/triangle.swift
2
2330
/** * https://leetcode.com/problems/triangle/ * * */ // Date: Sat Sep 12 16:03:03 PDT 2020 class Solution { /// - Complexity: /// - Time: O(n^2) /// - Space: O(n^2) func minimumTotal(_ triangle: [[Int]]) -> Int { let n = triangle.count var sum = triangle var minSum = Int.max for row in 0 ..< n { for col in 0 ... row { var left = Int.max var right = Int.max if row > 0 { if col != row { right = sum[row - 1][col] } if col > 0 { left = sum[row - 1][col - 1] } } else { left = 0 right = 0 } // print("\(row) : \(col) - \(left) - \(right)") sum[row][col] = triangle[row][col] + min(left, right) if row == n - 1 { minSum = min(minSum, sum[row][col]) } } } // print(sum) return minSum } }/** * https://leetcode.com/problems/triangle/ * * */ // Date: Sat Sep 12 16:08:06 PDT 2020 class Solution { /// - Complexity: /// - Time: O(n^2) /// - Space: O(2n) func minimumTotal(_ triangle: [[Int]]) -> Int { let n = triangle.count var sum = Array(repeating: Array(repeating: 0, count: n), count: 2) var minSum = Int.max for row in 0 ..< n { for col in 0 ... row { var left = Int.max var right = Int.max if row > 0 { if col != row { right = sum[(row + 1) % 2][col] } if col > 0 { left = sum[(row + 1) % 2][col - 1] } } else { left = 0 right = 0 } // print("\(row) : \(col) - \(left) - \(right)") sum[row % 2][col] = triangle[row][col] + min(left, right) if row == n - 1 { minSum = min(minSum, sum[row % 2][col]) } } } // print(sum) return minSum } }
mit
72a45159a66988daca2cccda99b77528
28.506329
75
0.351502
4.138544
false
false
false
false
modocache/Gift
Gift/Repository/Repository+Commit.swift
1
2760
import Foundation import LlamaKit import ReactiveCocoa public extension Repository { /** Enumerates the commits in a repository in the given order. :param: sorting The sorting rules to use when ordering commits to enumerate. :returns: A signal that will notify subscribers of commits as they are enumerated. Dispose of the signal in order to discontinue the enueration. */ public func commits(sorting: CommitSorting = CommitSorting.Time) -> SignalProducer<Commit, NSError> { return SignalProducer { (observer, disposable) in var out = COpaquePointer.null() let errorCode = git_revwalk_new(&out, self.cRepository) if errorCode == GIT_OK.value { CommitWalker(cWalker: out, cRepository: self.cRepository, sorting: sorting) .walk(observer, disposable: disposable) } else { sendError(observer, NSError.libGit2Error(errorCode, libGit2PointOfFailure: "git_revwalk_new")) } } } /** Sets the current HEAD of the repository to the given commit. Depending on the reset type specified, this may also reset the index and working directory. :param: commit The commit HEAD should be reset to. :param: resetType A type specifying whether the reset should be "soft", "hard", or "mixed"--each of those being different options for resetting the index and working directory. :param: checkoutOptions In the case of a hard commit, these options will be used to determine exactly how files will be reset. These can also be used in order to register progress callbacks. The "checkout strategy" of the options will be overridden based on the reset type. :param: signature The identity that will be used to popular the reflog entry. By default, this will be recorded as "com.libgit2.Gift". :returns: The result of the operation: either a repository that has been reset to point to the given commit, or an error indicating what went wrong. */ public func reset(commit: Commit, resetType: ResetType, checkoutOptions: CheckoutOptions = CheckoutOptions(strategy: CheckoutStrategy.None), signature: Signature = giftSignature) -> Result<Repository, NSError> { var cOptions = checkoutOptions.cOptions var cSignature = signature.cSignature let errorCode = git_reset(cRepository, commit.cCommit, git_reset_t(resetType.rawValue), &cOptions, &cSignature, nil) if errorCode == GIT_OK.value { return success(self) } else { return failure(NSError.libGit2Error(errorCode, libGit2PointOfFailure: "git_reset")) } } }
mit
f6b1cd96e6df90d9c15c8c30d86cf39a
48.285714
213
0.678261
4.677966
false
false
false
false
openHPI/xikolo-ios
iOS/ViewControllers/Courses/PDFViewController.swift
1
6093
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Common import PDFKit import UIKit import WebKit class PDFViewController: UIViewController { @IBOutlet private var shareButton: UIBarButtonItem! private var pdfView = PDFView() private lazy var progress: CircularProgressView = { let progress = CircularProgressView() progress.translatesAutoresizingMaskIntoConstraints = false progress.lineWidth = 4 progress.gapWidth = 2 progress.tintColor = Brand.default.colors.primary let progressValue: CGFloat? = nil progress.updateProgress(progressValue) return progress }() private lazy var downloadSession = URLSession(configuration: .default, delegate: self, delegateQueue: nil) private var tempPDFFile: TemporaryFile? { didSet { try? oldValue?.deleteDirectory() DispatchQueue.main.async { self.navigationItem.rightBarButtonItem = self.tempPDFFile != nil ? self.shareButton : nil } } } private var currentDownload: URLSessionDownloadTask? private var filename: String? private var url: URL? { didSet { guard self.viewIfLoaded != nil else { return } guard let url = self.url else { return } self.loadPDF(for: url) } } override func awakeFromNib() { super.awakeFromNib() self.view.addSubview(self.progress) NSLayoutConstraint.activate([ self.progress.centerXAnchor.constraint(equalTo: self.view.layoutMarginsGuide.centerXAnchor), self.progress.centerYAnchor.constraint(equalTo: self.view.layoutMarginsGuide.centerYAnchor), self.progress.heightAnchor.constraint(equalToConstant: 50), self.progress.widthAnchor.constraint(equalTo: self.progress.heightAnchor), ]) } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = nil self.initializePDFView() self.pdfView.isHidden = true self.progress.alpha = 0.0 if let url = self.url { self.loadPDF(for: url) } UIView.animate(withDuration: defaultAnimationDuration, delay: 0.5, options: .curveLinear) { self.progress.alpha = CGFloat(1.0) } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.currentDownload?.cancel() try? self.tempPDFFile?.deleteDirectory() } func configure(for url: URL, filename: String?) { self.url = url self.filename = filename } func initializePDFView() { self.view.addSubview(self.pdfView) self.pdfView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ self.pdfView.leadingAnchor.constraint(equalTo: view.leadingAnchor), self.pdfView.trailingAnchor.constraint(equalTo: view.trailingAnchor), self.pdfView.bottomAnchor.constraint(equalTo: view.bottomAnchor), self.pdfView.topAnchor.constraint(equalTo: view.topAnchor), ]) self.pdfView.autoScales = true if #available(iOS 12.0, *) { self.pdfView.pageShadowsEnabled = false } } private func loadPDF(for url: URL) { var request = URLRequest(url: url) request.setValue(Routes.Header.acceptPDF, forHTTPHeaderField: Routes.Header.acceptKey) for (key, value) in NetworkHelper.requestHeaders(for: url) { request.setValue(value, forHTTPHeaderField: key) } let task = self.downloadSession.downloadTask(with: request) self.currentDownload = task task.resume() } @IBAction private func sharePDF(_ sender: UIBarButtonItem) { guard let fileURL = self.tempPDFFile?.fileURL else { return } let activityViewController = UIActivityViewController(activityItems: [fileURL], applicationActivities: nil) activityViewController.popoverPresentationController?.barButtonItem = sender self.present(activityViewController, animated: trueUnlessReduceMotionEnabled) } } extension PDFViewController: URLSessionDownloadDelegate { func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { DispatchQueue.main.async { self.progress.updateProgress(1.0, animated: trueUnlessReduceMotionEnabled) } let filename: String = { if let filename = self.filename { return "\(filename).pdf" } if let suggestedFilename = downloadTask.response?.suggestedFilename { return suggestedFilename } if let requestURL = downloadTask.currentRequest?.url { return "\(requestURL.lastPathComponent).\(requestURL.pathExtension)" } return "file.pdf" }() do { let tmpFile = try TemporaryFile(creatingTempDirectoryForFilename: filename) try Data(contentsOf: location).write(to: tmpFile.fileURL) self.tempPDFFile = tmpFile DispatchQueue.main.async { self.pdfView.document = PDFDocument(url: tmpFile.fileURL) self.progress.isHidden = true self.pdfView.isHidden = false } self.currentDownload = nil } catch { logger.error("Error processing PDF", error: error) } } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let value = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite) DispatchQueue.main.async { self.progress.updateProgress(value, animated: trueUnlessReduceMotionEnabled) } } }
gpl-3.0
82be500259d10fb66da5e66a1c9bd7bb
32.657459
120
0.643795
5.302002
false
false
false
false
PurpleSweetPotatoes/SwiftKit
SwiftKit/extension/UIButton+extension.swift
1
6119
// // UIButton+extension.swift // swift4.2Demo // // Created by baiqiang on 2018/10/6. // Copyright © 2018年 baiqiang. All rights reserved. // import UIKit enum BtnSubViewAdjust { case none case left case right case imgTopTitleBottom } /// 按钮点击间隔时间,防止重复点击 private var _interval: TimeInterval = 1 extension UIButton { /// 倒计时功能 /// /// - Parameters: /// - startTime: 起始时间 /// - reduceTime: 递减时间 /// - action: 递减回调方法 func countDown(startTime: Int, reduceTime: Int,action: @escaping(_ sender: UIButton, _ currentTime: Int) -> Void) { self.countTime = startTime self.action = action self.timer?.cancel() self.timer = DispatchSource.makeTimerSource(queue:DispatchQueue.main) self.timer?.schedule(deadline: .now(), repeating: .seconds(reduceTime)) self.timer?.setEventHandler { [weak self] in if let actionBlock = self?.action { actionBlock(self!, self?.countTime ?? 0) } if self?.countTime == 0 { self?.isUserInteractionEnabled = true self?.timer?.cancel() } self?.countTime -= reduceTime } self.timer?.resume() self.isUserInteractionEnabled = false } /// 调整btn视图和文字位置() /// /// - Parameters: /// - spacing: 调整后的间距 /// - type: 调整方式BtnSubViewAdjust func adjustImageTitle(spacing: CGFloat, type: BtnSubViewAdjust) { //重置内间距、防止获取视图位置出错 self.imageEdgeInsets = UIEdgeInsets.zero self.titleEdgeInsets = UIEdgeInsets.zero if type == .none { return } guard let imgView = self.imageView, let titleLab = self.titleLabel else { print("check you btn have image and text!") return } let width = self.frame.width var imageLeft: CGFloat = 0 var imageTop: CGFloat = 0 var titleLeft: CGFloat = 0 var titleTop: CGFloat = 0 var titleRift: CGFloat = 0 if type == .imgTopTitleBottom { imageLeft = (width - imgView.frame.width) * 0.5 - imgView.frame.origin.x imageTop = spacing - imgView.frame.origin.y titleLeft = (width - titleLab.frame.width) * 0.5 - titleLab.frame.origin.x - titleLab.frame.origin.x titleTop = spacing * 2 + imgView.frame.height - titleLab.frame.origin.y titleRift = -titleLeft - titleLab.frame.origin.x * 2 } else if type == .left { imageLeft = spacing - imgView.frame.origin.x titleLeft = spacing * 2 + imgView.frame.width - titleLab.frame.origin.x titleRift = -titleLeft } else { titleLeft = width - titleLab.frame.maxX - spacing titleRift = -titleLeft imageLeft = width - imgView.right - spacing * 2 - titleLab.frame.width } self.imageEdgeInsets = UIEdgeInsets(top: imageTop, left: imageLeft, bottom: -imageTop, right: -imageLeft) self.titleEdgeInsets = UIEdgeInsets(top: titleTop, left: titleLeft, bottom: -titleTop, right: titleRift) } public class func startIntervalAction(interval: TimeInterval) { _interval = interval DispatchQueue.once(#function) { BQTool.exchangeMethod(cls: self, targetSel: #selector(UIButton.sendAction), newSel: #selector(UIButton.re_sendAction)) } } @objc private func re_sendAction(action: Selector, to target: AnyObject?, forEvent event: UIEvent?) { if self.isKind(of: UIButton.classForCoder()) { if self.isIgnoreEvent { return } else { self.perform(#selector(self.resetIgnoreEvent), with: nil, afterDelay: _interval) } } self.isIgnoreEvent = true self.re_sendAction(action: action, to: target, forEvent: event) } @objc private func resetIgnoreEvent() { self.isIgnoreEvent = false; } //MARK:- ***** Override func ***** open override func removeFromSuperview() { super.removeFromSuperview() self.timer?.cancel() } //MARK:- ***** Associated Object ***** typealias btnUpdateBlock = (_ sender: UIButton, _ currentTime: Int) -> Void private struct AssociatedKeys { static var countKey = "btn_countTime" static var timerKey = "btn_sourceTimer" static var actionKey = "btn_actionKey" static var isIgnoreEventKey = "btn_isIgnoreEventKey" } private var action: btnUpdateBlock? { get { return objc_getAssociatedObject(self, &AssociatedKeys.actionKey) as? btnUpdateBlock } set (newValue){ objc_setAssociatedObject(self, &AssociatedKeys.actionKey, newValue!, .OBJC_ASSOCIATION_COPY_NONATOMIC) } } private var timer: DispatchSourceTimer? { get { return objc_getAssociatedObject(self, &AssociatedKeys.timerKey) as? DispatchSourceTimer } set (newValue){ objc_setAssociatedObject(self, &AssociatedKeys.timerKey, newValue!, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } private var countTime: Int! { get { return (objc_getAssociatedObject(self, &AssociatedKeys.countKey) as! Int) } set (newValue){ objc_setAssociatedObject(self, &AssociatedKeys.countKey, newValue!, .OBJC_ASSOCIATION_ASSIGN) } } private var isIgnoreEvent: Bool! { get { return (objc_getAssociatedObject(self, &AssociatedKeys.isIgnoreEventKey) as? Bool) ?? false } set (newValue){ objc_setAssociatedObject(self, &AssociatedKeys.isIgnoreEventKey, newValue!, .OBJC_ASSOCIATION_ASSIGN) } } }
apache-2.0
1caf872b5d2813be4df73f68c7917a96
31.666667
130
0.585982
4.616216
false
false
false
false
netcosports/Gnomon
Sources/Decodable/Decodable.swift
1
2581
// // Created by Vladimir Burdukov on 27/10/17. // Copyright © 2017 NetcoSports. All rights reserved. // import Foundation #if SWIFT_PACKAGE import Gnomon #endif extension CodingUserInfoKey { static let xpath = CodingUserInfoKey(rawValue: "Gnomon.XPath")! } public protocol DecodableModel: BaseModel, Decodable where DataContainer == DecoderContainer { static var decoder: JSONDecoder { get } } public extension DecodableModel { static var decoder: JSONDecoder { return JSONDecoder() } static func dataContainer(with data: Data, at path: String?) throws -> DecoderContainer { let decoder = Self.decoder decoder.userInfo[.xpath] = path return try decoder.decode(DecoderContainer.self, from: data) } init(_ container: DecoderContainer) throws { try self.init(from: container.decoder) } } private struct EmptyDecoder: Decoder { let codingPath: [CodingKey] = [] let userInfo: [CodingUserInfoKey: Any] = [:] func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key: CodingKey { throw "decoder is empty" } func unkeyedContainer() throws -> UnkeyedDecodingContainer { throw "decoder is empty" } func singleValueContainer() throws -> SingleValueDecodingContainer { throw "decoder is empty" } } public struct UnkeyedDecodingContainerIterator: DataContainerIterator { var unkeyed: UnkeyedDecodingContainer init(_ unkeyed: UnkeyedDecodingContainer) { self.unkeyed = unkeyed } public var count: Int? { return unkeyed.count } public typealias Element = DecoderContainer public mutating func next() -> DecoderContainer? { if let decoder = try? unkeyed.superDecoder() { return DecoderContainer(decoder) } else { return nil } } } public struct DecoderContainer: DataContainerProtocol, Decodable { let decoder: Decoder init(_ decoder: Decoder) { self.decoder = decoder } public init(from decoder: Decoder) throws { self.decoder = try decoder.decoder(by: decoder.userInfo[.xpath] as? String) } public typealias Iterator = UnkeyedDecodingContainerIterator public static func container(with data: Data, at path: String?) throws -> DecoderContainer { throw "container should be parsed in DecodableModel" } public func multiple() -> UnkeyedDecodingContainerIterator? { guard let unkeyed = try? decoder.unkeyedContainer() else { return nil } return UnkeyedDecodingContainerIterator(unkeyed) } public static func empty() -> DecoderContainer { return DecoderContainer(EmptyDecoder()) } }
mit
4ffcde5159c4f08335901fe7478dc827
23.571429
106
0.726357
4.699454
false
false
false
false
Sadmansamee/quran-ios
Quran/ShareController/ShareController.swift
1
1040
// // ShareController.swift // Quran // // Created by Hossam Ghareeb on 6/20/16. // Copyright © 2016 Quran.com. All rights reserved. // import UIKit class ShareController: NSObject { class func showShareActivityWithText(_ text: String, image: UIImage? = nil, url: URL? = nil, sourceViewController: UIViewController, handler: UIActivityViewControllerCompletionWithItemsHandler?) { var itemsToShare = [AnyObject]() itemsToShare.append(text as AnyObject) if let shareImage = image { itemsToShare.append(shareImage) } if let shareURL = url { itemsToShare.append(shareURL as AnyObject) } let activityViewController = UIActivityViewController(activityItems: itemsToShare, applicationActivities: nil) activityViewController.completionWithItemsHandler = handler sourceViewController.present(activityViewController, animated: true, completion: nil) } }
mit
13cf4acde0e27b0eacc34383277f524a
33.633333
118
0.651588
5.526596
false
false
false
false
azawawi/SwiftyZeroMQ
Tests/ZeroMQTests.swift
1
6579
// // Copyright (c) 2016-2017 Ahmad M. Zawawi (azawawi) // // This package is distributed under the terms of the MIT license. // Please see the accompanying LICENSE file for the full text of the license. // import XCTest @testable import SwiftyZeroMQ class ZeroMQTests: XCTestCase { func testVersion() { let (major, minor, patch, versionString) = SwiftyZeroMQ.version XCTAssertTrue(major == 4, "Major version is 4") XCTAssertTrue(minor == 2, "Minor version is 2") XCTAssertTrue(patch == 2, "Patch version is 2") XCTAssertTrue(versionString == "\(major).\(minor).\(patch)") let frameworkVersion = SwiftyZeroMQ.frameworkVersion let regex = "^\\d+\\.\\d+\\.\\d+$" XCTAssertTrue(frameworkVersion.range(of: regex, options : .regularExpression) != nil) } func testHas() { let _ = SwiftyZeroMQ.has(.ipc) XCTAssertTrue(true, ".ipc works") let _ = SwiftyZeroMQ.has(.pgm) XCTAssertTrue(true, ".pgm works") let _ = SwiftyZeroMQ.has(.tipc) XCTAssertTrue(true, ".tipc works") let _ = SwiftyZeroMQ.has(.norm) XCTAssertTrue(true, ".norm works") let _ = SwiftyZeroMQ.has(.curve) XCTAssertTrue(true, ".curve works") let _ = SwiftyZeroMQ.has(.gssapi) XCTAssertTrue(true, ".gssapi works") } func testContext() { do { let context = try SwiftyZeroMQ.Context() XCTAssertTrue(true, "Context created") XCTAssertTrue(context.handle != nil, "socket.handle is not nil") // blocky XCTAssertTrue( try context.isBlocky(), "Default value for blocky is true" ) let newBlockyValue = false try context.setBlocky(newBlockyValue) XCTAssertTrue( try context.isBlocky() == newBlockyValue, "blocky setter works" ) // ioThreads XCTAssertTrue( try context.getIOThreads() == 1, "Default value for ioThreads is 1" ) let newIoThread = 2 try context.setIOThreads(newIoThread) XCTAssertTrue( try context.getIOThreads() == newIoThread, "ioThreads setter works" ) // maxSockets and socketLimit let socketLimit = try context.getSocketLimit() XCTAssertTrue( socketLimit > 0, "Default value for socketLimit > 0" ) XCTAssertTrue( try context.getMaxSockets() <= socketLimit, "Default value for maxSockets <= socketLimit" ) let newMaxSockets = 2 try context.setMaxSockets(newMaxSockets) XCTAssertTrue( try context.getMaxSockets() == newMaxSockets, "maxSockets setter works" ) // ipv6Enabled XCTAssertFalse( try context.isIPV6Enabled(), "Default value for IPV6Enabled is false" ) let newIpv6Enabled = true try context.setIPV6Enabled(newIpv6Enabled) XCTAssertTrue( try context.isIPV6Enabled() == newIpv6Enabled, "IPV6Enabled setter works" ) // setThreadPriority try context.setThreadPriority(10) XCTAssertTrue(true, "Context setThreadPriority works") // maxMessageSize XCTAssertTrue( try context.getMaxMessageSize() == Int(Int32.max), "Default value for max message size is Int32.max" ) let newMaxMessageSize = 4096 try context.setMaxMessageSize(newMaxMessageSize) XCTAssertTrue( try context.getMaxMessageSize() == newMaxMessageSize, "maxMessageSize setter works" ) // setThreadSchedulingPolicy try context.setThreadSchedulingPolicy(5) XCTAssertTrue(true, "Context setThreadSchedulingPolicy works") // Hashable let c1 = try SwiftyZeroMQ.Context() let c2 = try SwiftyZeroMQ.Context() let contextMap = [ c1: "c1", c2: "c2"] XCTAssertTrue(contextMap[c1] == "c1", "Correct string value for c1") XCTAssertTrue(contextMap[c2] == "c2", "Correct string value for c2") } catch { XCTFail("Context tests failure") } } func testSocket() { do { // Test creation of all socket types let socketTypes : [SwiftyZeroMQ.SocketType] = [ .request, .reply, .router, .dealer, .publish, .subscribe, .xpublish, .xsubscribe, .push, .pull, .pair, .stream ] for socketType in socketTypes { let context = try SwiftyZeroMQ.Context() let socket = try context.socket(socketType) XCTAssertTrue(socket.handle != nil, "socket.handle is not nil") XCTAssertTrue(true, "\(socketType) socket created") } // Hashable let context = try SwiftyZeroMQ.Context() let s1 = try context.socket(.request) let s2 = try context.socket(.request) let socketMap = [ s1: "s1", s2: "s2"] XCTAssertTrue(socketMap[s1] == "s1", "Correct string value for s1") XCTAssertTrue(socketMap[s2] == "s2", "Correct string value for s2") } catch { XCTFail("Socket tests failure") } } /** Test a simple request-reply pattern example without blocking */ func testRequestReplyPattern() { do { // Define a TCP endpoint along with the text that we are going to send/recv let endpoint = "tcp://127.0.0.1:5555" let textToBeSent = "Hello world" // Request socket let context = try SwiftyZeroMQ.Context() // Reply socket (goes first let replier = try context.socket(.reply) try replier.bind(endpoint) // Request socket let requestor = try context.socket(.request) try requestor.connect(endpoint) // Send it without waiting and check the reply on other socket try requestor.send(string: textToBeSent, options: .dontWait) let reply = try replier.recv() XCTAssertTrue(reply == textToBeSent, "Got the reply that we sent over ZeroMQ socket") } catch { XCTFail("Request-reply pattern failure") } } }
mit
d6f11ebc3e3060ae5caa11575cfff6f9
37.25
97
0.568323
4.844624
false
true
false
false
SPECURE/rmbt-ios-client
Sources/ServiceTypeMapping.swift
1
2087
/***************************************************************************************************** * Copyright 2014-2016 SPECURE GmbH * * 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 #if swift(>=3.2) import Darwin import dnssd #else import RMBTClientPrivate #endif // TODO: is this the Rcode? /* enum DNSStatus { OK = 0 BAD_HANDLE = 1 MALFORMED_QUERY = 2 TIMEOUT = 3 SEND_FAILED = 4 RECEIVE_FAILED = 5 CONNECTION_FAILED = 6 WRONG_SERVER = 7 WRONG_XID = 8 WRONG_QUESTION = 9 } */ let DNSServiceTypeStrToInt: [String: Int] = [ "A": kDNSServiceType_A, // "NS": kDNSServiceType_NS, "CNAME": kDNSServiceType_CNAME, // "SOA": kDNSServiceType_SOA, // "PTR": kDNSServiceType_PTR, "MX": kDNSServiceType_MX, // "TXT": kDNSServiceType_TXT, "AAAA": kDNSServiceType_AAAA, // "SRV": kDNSServiceType_SRV, //"A6": kDNSServiceType_A6, // "SPF": kDNSServiceType_SPF ] let DNSServiceTypeIntToStr: [Int: String] = [ kDNSServiceType_A: "A", // kDNSServiceType_NS: "NS", kDNSServiceType_CNAME: "CNAME", // kDNSServiceType_SOA: "SOA", // kDNSServiceType_PTR: "PTR", kDNSServiceType_MX: "MX", // kDNSServiceType_TXT: "TXT", kDNSServiceType_AAAA: "AAAA", // kDNSServiceType_SRV: "SRV", //kDNSServiceType_A6: "A6", // kDNSServiceType_SPF: "SPF" ]
apache-2.0
77dc7c411405eea9f8d5463b4d555da8
31.107692
103
0.570196
3.937736
false
false
false
false
material-motion/material-motion-swift
tests/unit/properties/PropertyObservation.swift
1
1011
/* Copyright 2016-present The Material Motion Authors. 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 XCTest @testable import MaterialMotion class PropertyObservation: XCTestCase { func testUpdatesObserverImmediately() { let point = CGPoint(x: 100, y: 100) let property = createProperty(withInitialValue: point) var observedValue: CGPoint? = nil let _ = property.subscribeToValue { value in observedValue = value } XCTAssertEqual(observedValue!, point) } }
apache-2.0
f8b6b99e92cbf41d7bc09850d010290b
30.59375
73
0.755687
4.616438
false
true
false
false
gaurav1981/SwiftStructures
SwiftTests/ListTest.swift
1
2676
// // ListTest.swift // SwiftStructures // // Created by Wayne Bishop on 7/6/16. // Copyright © 2016 Arbutus Software Inc. All rights reserved. // import XCTest @testable import SwiftStructures class ListTest: XCTestCase { override func setUp() { super.setUp() } //test strings func testStringList() { /* note: each element has its own potential 'slot' in the hash list. In this scenario, the hash table algorithm will implement 'separate chaining' to support 'hash collisions'. */ //new string list let slist = HashList<String>(capacity: 3) _ = slist.append("Wayne Bishop") _ = slist.append("Frank Smith") _ = slist.append("Jennifer Hobbs") _ = slist.append("Tim Cook") _ = slist.append("Steve Jobs") _ = slist.append("Wayne Bishop") //should produce collision _ = slist.append("Larry Page") _ = slist.append("Albert Einstien") //obtain element let element = slist.getElement(with: "Frank Smith") if let results = element.0 { let rString: String? = results.element print("element with value: \(rString)") } else { XCTFail("value not retreived..") } } //test verticies - custom func testVertexList() { /* note: for this test, the added element is a custom object. using this technique, any potential object could be used. */ let testVertex: Vertex = Vertex() testVertex.key = "A" let vList: HashList = HashList<Vertex>(capacity: 10) _ = vList.append(testVertex) //obtain element let element = vList.getElement(with: "A") if let results = element.0 { let rVertex: Vertex? = results.element print("element with key \(rVertex?.key)") } else { XCTFail("element not retreived..") } } //test floats func testMissingList() { //new float list let fList = HashList<Float>(capacity: 5) _ = fList.append(10.2) _ = fList.append(8.6) //element doesn't exist.. let element = fList.getElement(with: String(3.7)) if element.1 != HashResults.NotFound { XCTFail("element incorrectly found..") } } }
mit
5af27ade7db9843e0392f3f7054e8716
21.669492
68
0.503925
4.759786
false
true
false
false
jeancarlosaps/swift
Swift em 4 Semanas/Desafios/Desafios Semana 3.playground/Contents.swift
2
4806
// Playground - noun: a place where people can play import UIKit /* __ __ __ \ / __ / \ | / \ \|/ Mobgeek _,.---v---._ /\__/\ / \ Curso Swift em 4 semanas \_ _/ / \ \ \_| @ __| \ \_ \ ,__/ / ~~~`~~~~~~~~~~~~~~/~~~~ */ /*: # **Exercícios práticos - Semana 3** 1 - Use class precedida pelo nome da classe para criar uma classe. Uma propriedade de declaração em uma classe é escrita da mesma forma que uma declaração de uma constante ou variável, exceto que ela é escrita dentro do contexto da classe. Declarações de métodos são escritos da mesma forma que funções. Veja o seguinte exemplo de uma forma geométrica: */ /* class Forma { var númeroDeLados = 0 func descriçãoSimples() -> String { return "Uma forma com \(númeroDeLados) lados." } } */ /*: **Desafio 1:** Adicione uma propriedade constante usando `let`, e adicione um outro método que usa um argumento para comparar se duas formas geométricas possuem o mesmo número de lados. Resposta: */ /*: --- 2 - Agora que já criamos uma classe `Forma`, que será o nosso molde para criar diferentes formas, que tal começarmos a acessar suas propriedades e métodos? **Desafio 2:** Usando a classe `Forma` no exercício 1, crie uma instância inserindo parêntesis após o nome da classe. Use o dot syntax (sintaxe do ponto) para acessar as propriedades e métodos de uma instância. Resposta: */ /*: --- 3 - Até agora utilizamos o inicializador padrão fornecido pela classe Forma quando nenhum inicializador é informado. Que agora criarmos nossos próprios inicializadores customizados? **Desafio 3:** Nesta versão de classe `Forma` há algo importante que está faltando: um inicializador para invocar uma classe quando uma instância for criada. Complete o exercício abaixo usando `init`, `self` e `func`. */ // class NomeDaForma{ // var númeroDeLados: Int = 0 // var nome: String //: Resposta: /*: --- 4 - Métodos de uma classe que sobreescrevem (conhecidos em inglês como override) a implementação de uma subclasse são iniciados com override. O compliador também consegue detectar métodos com override que na realidade não estão sobreescrevendo nenhum método na subclasse. Veja o seguinte exemplo: */ /* class Quadrado: NomeDaForma { var comprimentoLado: Double init(comprimentoLado: Double, nome: String) { self.comprimentoLado = comprimentoLado super.init(nome: nome) númeroDeLados = 4 } func área() -> Double { return comprimentoLado * comprimentoLado } override func descriçãoSimples() -> String { return "Um quadrado com o comprimento dos lados \(comprimentoLado)." } } let teste = Quadrado(comprimentoLado: 5.2, nome: "meu quadrado teste") teste.área() teste.descriçãoSimples() */ /*: **Desafio 4:** Crie outra subclasse de `NomeDaForma` chamada de `Círculo` que possui um raio e um nome como argumentos para seu inicializador. Implemente um método de área e de `descriçãoSimples` para a classe `Círculo`. Resposta: */ /*: --- 5 - Além de propriedades de armazemento que apenas guardam algum valor, existem as propriedades computadas que calculam um valor. **Desafio 5:** Relembrando que além de propriedades armazenada, classes, estruturas e enumerações podem definir propriedades computadas. Complete a sintaxe abaixo de um triângulo equilátero usando um `getter`, um `setter` e uma `func override`. Resposta: */ /* class TriânguloEquilátero: NomeDaForma{ var comprimentoDoLado: Double = 0.0 init(comprimentoDoLado: Double, nome: String) { self.comprimentoDoLado = comprimentoDoLado super.init(nome: nome) númeroDeLados = 3 } var perímetro: Double { … } … } */ /*: --- **Desafio Extra:** NTFPN*: Você pode precisar responder a atualização do valor de uma propriedade, em vez de ter que calcular uma propriedade como no exemplo anterior. Use os observadores de propriedades `willSet` e `didSet` para fornecer código que seja executado antes e/ou depois de um novo valor ser armazenado em uma propriedade. Usando estes observadores de propriedades no Playground, invoque um método de uma classe que você irá criar chamada `TriânguloEQuadrado` que garanta que o comprimento do lado do triângulo equilátero seja sempre igual ao comprimento do lado do quadrado. *NTFPN: "Não tá fácil pra ninguém" Resposta: */
mit
ebdccd7b14c7e434a51fab5404ded151
30.413333
588
0.660654
3.492958
false
false
false
false
DarrenKong/firefox-ios
Client/Frontend/Browser/BrowserViewController.swift
1
126101
/* 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 Photos import UIKit import WebKit import Shared import Storage import SnapKit import XCGLogger import Alamofire import Account import ReadingList import MobileCoreServices import SDWebImage import SwiftyJSON import Telemetry import Sentry private let KVOs: [KVOConstants] = [ .estimatedProgress, .loading, .canGoBack, .canGoForward, .URL, .title, ] private let ActionSheetTitleMaxLength = 120 private struct BrowserViewControllerUX { fileprivate static let BackgroundColor = UIConstants.AppBackgroundColor fileprivate static let ShowHeaderTapAreaHeight: CGFloat = 32 fileprivate static let BookmarkStarAnimationDuration: Double = 0.5 fileprivate static let BookmarkStarAnimationOffset: CGFloat = 80 } class BrowserViewController: UIViewController { var homePanelController: HomePanelViewController? var webViewContainer: UIView! var urlBar: URLBarView! var clipboardBarDisplayHandler: ClipboardBarDisplayHandler? var readerModeBar: ReaderModeBarView? var readerModeCache: ReaderModeCache let webViewContainerToolbar = UIView() var statusBarOverlay: UIView! fileprivate(set) var toolbar: TabToolbar? fileprivate var searchController: SearchViewController? fileprivate var screenshotHelper: ScreenshotHelper! fileprivate var homePanelIsInline = false fileprivate var searchLoader: SearchLoader? fileprivate let alertStackView = UIStackView() // All content that appears above the footer should be added to this view. (Find In Page/SnackBars) fileprivate var findInPageBar: FindInPageBar? lazy var mailtoLinkHandler: MailtoLinkHandler = MailtoLinkHandler() lazy fileprivate var customSearchEngineButton: UIButton = { let searchButton = UIButton() searchButton.setImage(UIImage(named: "AddSearch")?.withRenderingMode(.alwaysTemplate), for: []) searchButton.addTarget(self, action: #selector(addCustomSearchEngineForFocusedElement), for: .touchUpInside) searchButton.accessibilityIdentifier = "BrowserViewController.customSearchEngineButton" return searchButton }() fileprivate var customSearchBarButton: UIBarButtonItem? // popover rotation handling fileprivate var displayedPopoverController: UIViewController? fileprivate var updateDisplayedPopoverProperties: (() -> Void)? var openInHelper: OpenInHelper? // location label actions fileprivate var pasteGoAction: AccessibleAction! fileprivate var pasteAction: AccessibleAction! fileprivate var copyAddressAction: AccessibleAction! fileprivate weak var tabTrayController: TabTrayController! let profile: Profile let tabManager: TabManager // These views wrap the urlbar and toolbar to provide background effects on them var header: UIView! var footer: UIView! fileprivate var topTouchArea: UIButton! let urlBarTopTabsContainer = UIView(frame: CGRect.zero) var topTabsVisible: Bool { return topTabsViewController != nil } // Backdrop used for displaying greyed background for private tabs var webViewContainerBackdrop: UIView! var scrollController = TabScrollingController() fileprivate var keyboardState: KeyboardState? var pendingToast: ButtonToast? // A toast that might be waiting for BVC to appear before displaying // Tracking navigation items to record history types. // TODO: weak references? var ignoredNavigation = Set<WKNavigation>() var typedNavigation = [WKNavigation: VisitType]() var navigationToolbar: TabToolbarProtocol { return toolbar ?? urlBar } var topTabsViewController: TopTabsViewController? let topTabsContainer = UIView() init(profile: Profile, tabManager: TabManager) { self.profile = profile self.tabManager = tabManager self.readerModeCache = DiskReaderModeCache.sharedInstance super.init(nibName: nil, bundle: nil) didInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) displayedPopoverController?.dismiss(animated: true) { self.displayedPopoverController = nil } if let _ = self.presentedViewController as? PhotonActionSheet { self.presentedViewController?.dismiss(animated: true, completion: nil) } coordinator.animate(alongsideTransition: { context in self.scrollController.updateMinimumZoom() self.topTabsViewController?.scrollToCurrentTab(false, centerCell: false) if let popover = self.displayedPopoverController { self.updateDisplayedPopoverProperties?() self.present(popover, animated: true, completion: nil) } }, completion: { _ in self.scrollController.setMinimumZoom() }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } fileprivate func didInit() { screenshotHelper = ScreenshotHelper(controller: self) tabManager.addDelegate(self) tabManager.addNavigationDelegate(self) } override var preferredStatusBarStyle: UIStatusBarStyle { let isPrivate = tabManager.selectedTab?.isPrivate ?? false let isIpad = shouldShowTopTabsForTraitCollection(traitCollection) return (isPrivate || isIpad) ? .lightContent : .default } func shouldShowFooterForTraitCollection(_ previousTraitCollection: UITraitCollection) -> Bool { return previousTraitCollection.verticalSizeClass != .compact && previousTraitCollection.horizontalSizeClass != .regular } func shouldShowTopTabsForTraitCollection(_ newTraitCollection: UITraitCollection) -> Bool { return newTraitCollection.verticalSizeClass == .regular && newTraitCollection.horizontalSizeClass == .regular } func toggleSnackBarVisibility(show: Bool) { if show { UIView.animate(withDuration: 0.1, animations: { self.alertStackView.isHidden = false }) } else { alertStackView.isHidden = true } } fileprivate func updateToolbarStateForTraitCollection(_ newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator? = nil) { let showToolbar = shouldShowFooterForTraitCollection(newCollection) let showTopTabs = shouldShowTopTabsForTraitCollection(newCollection) urlBar.topTabsIsShowing = showTopTabs urlBar.setShowToolbar(!showToolbar) toolbar?.removeFromSuperview() toolbar?.tabToolbarDelegate = nil toolbar = nil if showToolbar { toolbar = TabToolbar() footer.addSubview(toolbar!) toolbar?.tabToolbarDelegate = self let theme = (tabManager.selectedTab?.isPrivate ?? false) ? Theme.Private : Theme.Normal toolbar?.applyTheme(theme) updateTabCountUsingTabManager(self.tabManager) } if showTopTabs { if topTabsViewController == nil { let topTabsViewController = TopTabsViewController(tabManager: tabManager) topTabsViewController.delegate = self addChildViewController(topTabsViewController) topTabsViewController.view.frame = topTabsContainer.frame topTabsContainer.addSubview(topTabsViewController.view) topTabsViewController.view.snp.makeConstraints { make in make.edges.equalTo(topTabsContainer) make.height.equalTo(TopTabsUX.TopTabsViewHeight) } self.topTabsViewController = topTabsViewController } topTabsContainer.snp.updateConstraints { make in make.height.equalTo(TopTabsUX.TopTabsViewHeight) } } else { topTabsContainer.snp.updateConstraints { make in make.height.equalTo(0) } topTabsViewController?.view.removeFromSuperview() topTabsViewController?.removeFromParentViewController() topTabsViewController = nil } view.setNeedsUpdateConstraints() if let home = homePanelController { home.view.setNeedsUpdateConstraints() } if let tab = tabManager.selectedTab, let webView = tab.webView { updateURLBarDisplayURL(tab) navigationToolbar.updateBackStatus(webView.canGoBack) navigationToolbar.updateForwardStatus(webView.canGoForward) navigationToolbar.updateReloadStatus(tab.loading) } } override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) { super.willTransition(to: newCollection, with: coordinator) // During split screen launching on iPad, this callback gets fired before viewDidLoad gets a chance to // set things up. Make sure to only update the toolbar state if the view is ready for it. if isViewLoaded { updateToolbarStateForTraitCollection(newCollection, withTransitionCoordinator: coordinator) } displayedPopoverController?.dismiss(animated: true, completion: nil) coordinator.animate(alongsideTransition: { context in self.scrollController.showToolbars(animated: false) if self.isViewLoaded { self.statusBarOverlay.backgroundColor = self.shouldShowTopTabsForTraitCollection(self.traitCollection) ? UIColor.Defaults.Grey80 : self.urlBar.backgroundColor self.setNeedsStatusBarAppearanceUpdate() } }, completion: nil) } func SELappDidEnterBackgroundNotification() { displayedPopoverController?.dismiss(animated: false) { self.displayedPopoverController = nil } } func SELtappedTopArea() { scrollController.showToolbars(animated: true) } func SELappWillResignActiveNotification() { // Dismiss any popovers that might be visible displayedPopoverController?.dismiss(animated: false) { self.displayedPopoverController = nil } // If we are displying a private tab, hide any elements in the tab that we wouldn't want shown // when the app is in the home switcher guard let privateTab = tabManager.selectedTab, privateTab.isPrivate else { return } webViewContainerBackdrop.alpha = 1 webViewContainer.alpha = 0 urlBar.locationContainer.alpha = 0 topTabsViewController?.switchForegroundStatus(isInForeground: false) presentedViewController?.popoverPresentationController?.containerView?.alpha = 0 presentedViewController?.view.alpha = 0 } func SELappDidBecomeActiveNotification() { // Re-show any components that might have been hidden because they were being displayed // as part of a private mode tab UIView.animate(withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: { self.webViewContainer.alpha = 1 self.urlBar.locationContainer.alpha = 1 self.topTabsViewController?.switchForegroundStatus(isInForeground: true) self.presentedViewController?.popoverPresentationController?.containerView?.alpha = 1 self.presentedViewController?.view.alpha = 1 self.view.backgroundColor = UIColor.clear }, completion: { _ in self.webViewContainerBackdrop.alpha = 0 }) // Re-show toolbar which might have been hidden during scrolling (prior to app moving into the background) scrollController.showToolbars(animated: false) } override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(SELappWillResignActiveNotification), name: .UIApplicationWillResignActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(SELappDidBecomeActiveNotification), name: .UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(SELappDidEnterBackgroundNotification), name: .UIApplicationDidEnterBackground, object: nil) KeyboardHelper.defaultHelper.addDelegate(self) webViewContainerBackdrop = UIView() webViewContainerBackdrop.backgroundColor = UIColor.gray webViewContainerBackdrop.alpha = 0 view.addSubview(webViewContainerBackdrop) webViewContainer = UIView() webViewContainer.addSubview(webViewContainerToolbar) view.addSubview(webViewContainer) // Temporary work around for covering the non-clipped web view content statusBarOverlay = UIView() view.addSubview(statusBarOverlay) topTouchArea = UIButton() topTouchArea.isAccessibilityElement = false topTouchArea.addTarget(self, action: #selector(SELtappedTopArea), for: .touchUpInside) view.addSubview(topTouchArea) // Setup the URL bar, wrapped in a view to get transparency effect urlBar = URLBarView() urlBar.translatesAutoresizingMaskIntoConstraints = false urlBar.delegate = self urlBar.tabToolbarDelegate = self header = urlBarTopTabsContainer urlBarTopTabsContainer.addSubview(urlBar) urlBarTopTabsContainer.addSubview(topTabsContainer) view.addSubview(header) // UIAccessibilityCustomAction subclass holding an AccessibleAction instance does not work, thus unable to generate AccessibleActions and UIAccessibilityCustomActions "on-demand" and need to make them "persistent" e.g. by being stored in BVC pasteGoAction = AccessibleAction(name: NSLocalizedString("Paste & Go", comment: "Paste the URL into the location bar and visit"), handler: { () -> Bool in if let pasteboardContents = UIPasteboard.general.string { self.urlBar(self.urlBar, didSubmitText: pasteboardContents) return true } return false }) pasteAction = AccessibleAction(name: NSLocalizedString("Paste", comment: "Paste the URL into the location bar"), handler: { () -> Bool in if let pasteboardContents = UIPasteboard.general.string { // Enter overlay mode and make the search controller appear. self.urlBar.enterOverlayMode(pasteboardContents, pasted: true, search: true) return true } return false }) copyAddressAction = AccessibleAction(name: NSLocalizedString("Copy Address", comment: "Copy the URL from the location bar"), handler: { () -> Bool in if let url = self.urlBar.currentURL { UIPasteboard.general.url = url as URL } return true }) view.addSubview(alertStackView) footer = UIView() view.addSubview(footer) alertStackView.axis = .vertical alertStackView.alignment = .center if AppConstants.MOZ_CLIPBOARD_BAR { clipboardBarDisplayHandler = ClipboardBarDisplayHandler(prefs: profile.prefs, tabManager: tabManager) clipboardBarDisplayHandler?.delegate = self } scrollController.urlBar = urlBar scrollController.header = header scrollController.footer = footer scrollController.snackBars = alertStackView scrollController.webViewContainerToolbar = webViewContainerToolbar self.updateToolbarStateForTraitCollection(self.traitCollection) setupConstraints() // Setup UIDropInteraction to handle dragging and dropping // links into the view from other apps. if #available(iOS 11, *) { let dropInteraction = UIDropInteraction(delegate: self) view.addInteraction(dropInteraction) } } fileprivate func setupConstraints() { topTabsContainer.snp.makeConstraints { make in make.leading.trailing.equalTo(self.header) make.top.equalTo(urlBarTopTabsContainer) } urlBar.snp.makeConstraints { make in make.leading.trailing.bottom.equalTo(urlBarTopTabsContainer) make.height.equalTo(UIConstants.TopToolbarHeight) make.top.equalTo(topTabsContainer.snp.bottom) } header.snp.makeConstraints { make in scrollController.headerTopConstraint = make.top.equalTo(self.topLayoutGuide.snp.bottom).constraint make.left.right.equalTo(self.view) } webViewContainerBackdrop.snp.makeConstraints { make in make.edges.equalTo(webViewContainer) } webViewContainerToolbar.snp.makeConstraints { make in make.left.right.top.equalTo(webViewContainer) make.height.equalTo(0) } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() statusBarOverlay.snp.remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(self.topLayoutGuide.length) } } override var canBecomeFirstResponder: Bool { return true } override func becomeFirstResponder() -> Bool { // Make the web view the first responder so that it can show the selection menu. return tabManager.selectedTab?.webView?.becomeFirstResponder() ?? false } func loadQueuedTabs(receivedURLs: [URL]? = nil) { // Chain off of a trivial deferred in order to run on the background queue. succeed().upon() { res in self.dequeueQueuedTabs(receivedURLs: receivedURLs ?? []) } } fileprivate func dequeueQueuedTabs(receivedURLs: [URL]) { assert(!Thread.current.isMainThread, "This must be called in the background.") self.profile.queue.getQueuedTabs() >>== { cursor in // This assumes that the DB returns rows in some kind of sane order. // It does in practice, so WFM. if cursor.count > 0 { // Filter out any tabs received by a push notification to prevent dupes. let urls = cursor.flatMap { $0?.url.asURL }.filter { !receivedURLs.contains($0) } if !urls.isEmpty { DispatchQueue.main.async { self.tabManager.addTabsForURLs(urls, zombie: false) } } // Clear *after* making an attempt to open. We're making a bet that // it's better to run the risk of perhaps opening twice on a crash, // rather than losing data. self.profile.queue.clearQueuedTabs() } // Then, open any received URLs from push notifications. if !receivedURLs.isEmpty { DispatchQueue.main.async { let unopenedReceivedURLs = receivedURLs.filter { self.tabManager.getTabForURL($0) == nil } self.tabManager.addTabsForURLs(unopenedReceivedURLs, zombie: false) if let lastURL = receivedURLs.last, let tab = self.tabManager.getTabForURL(lastURL) { self.tabManager.selectTab(tab) } } } } } // Because crashedLastLaunch is sticky, it does not get reset, we need to remember its // value so that we do not keep asking the user to restore their tabs. var displayedRestoreTabsAlert = false override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // On iPhone, if we are about to show the On-Boarding, blank out the tab so that it does // not flash before we present. This change of alpha also participates in the animation when // the intro view is dismissed. if UIDevice.current.userInterfaceIdiom == .phone { self.view.alpha = (profile.prefs.intForKey(PrefsKeys.IntroSeen) != nil) ? 1.0 : 0.0 } if !displayedRestoreTabsAlert && !cleanlyBackgrounded() && crashedLastLaunch() { displayedRestoreTabsAlert = true showRestoreTabsAlert() } else { tabManager.restoreTabs() } updateTabCountUsingTabManager(tabManager, animated: false) clipboardBarDisplayHandler?.checkIfShouldDisplayBar() } fileprivate func crashedLastLaunch() -> Bool { return Sentry.crashedLastLaunch } fileprivate func cleanlyBackgrounded() -> Bool { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return false } return appDelegate.applicationCleanlyBackgrounded } fileprivate func showRestoreTabsAlert() { guard canRestoreTabs() else { self.tabManager.addTabAndSelect() return } let alert = UIAlertController.restoreTabsAlert( okayCallback: { _ in self.tabManager.restoreTabs() }, noCallback: { _ in self.tabManager.addTabAndSelect() } ) self.present(alert, animated: true, completion: nil) } fileprivate func canRestoreTabs() -> Bool { guard let tabsToRestore = TabManager.tabsToRestore() else { return false } return !tabsToRestore.isEmpty } override func viewDidAppear(_ animated: Bool) { presentIntroViewController() self.webViewContainerToolbar.isHidden = false screenshotHelper.viewIsVisible = true screenshotHelper.takePendingScreenshots(tabManager.tabs) super.viewDidAppear(animated) if shouldShowWhatsNewTab() { // Only display if the SUMO topic has been configured in the Info.plist (present and not empty) if let whatsNewTopic = AppInfo.whatsNewTopic, whatsNewTopic != "" { if let whatsNewURL = SupportUtils.URLForTopic(whatsNewTopic) { self.openURLInNewTab(whatsNewURL, isPrivileged: false) profile.prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey) } } } if let toast = self.pendingToast { self.pendingToast = nil show(buttonToast: toast, afterWaiting: ButtonToastUX.ToastDelay) } showQueuedAlertIfAvailable() } // THe logic for shouldShowWhatsNewTab is as follows: If we do not have the LatestAppVersionProfileKey in // the profile, that means that this is a fresh install and we do not show the What's New. If we do have // that value, we compare it to the major version of the running app. If it is different then this is an // upgrade, downgrades are not possible, so we can show the What's New page. fileprivate func shouldShowWhatsNewTab() -> Bool { guard let latestMajorAppVersion = profile.prefs.stringForKey(LatestAppVersionProfileKey)?.components(separatedBy: ".").first else { return false // Clean install, never show What's New } return latestMajorAppVersion != AppInfo.majorAppVersion && DeviceInfo.hasConnectivity() } fileprivate func showQueuedAlertIfAvailable() { if let queuedAlertInfo = tabManager.selectedTab?.dequeueJavascriptAlertPrompt() { let alertController = queuedAlertInfo.alertController() alertController.delegate = self present(alertController, animated: true, completion: nil) } } override func viewWillDisappear(_ animated: Bool) { screenshotHelper.viewIsVisible = false super.viewWillDisappear(animated) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) } func resetBrowserChrome() { // animate and reset transform for tab chrome urlBar.updateAlphaForSubviews(1) footer.alpha = 1 [header, footer, readerModeBar].forEach { view in view?.transform = .identity } statusBarOverlay.isHidden = false } override func updateViewConstraints() { super.updateViewConstraints() topTouchArea.snp.remakeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(BrowserViewControllerUX.ShowHeaderTapAreaHeight) } readerModeBar?.snp.remakeConstraints { make in make.top.equalTo(self.header.snp.bottom) make.height.equalTo(UIConstants.ToolbarHeight) make.leading.trailing.equalTo(self.view) } webViewContainer.snp.remakeConstraints { make in make.left.right.equalTo(self.view) if let readerModeBarBottom = readerModeBar?.snp.bottom { make.top.equalTo(readerModeBarBottom) } else { make.top.equalTo(self.header.snp.bottom) } let findInPageHeight = (findInPageBar == nil) ? 0 : UIConstants.ToolbarHeight if let toolbar = self.toolbar { make.bottom.equalTo(toolbar.snp.top).offset(-findInPageHeight) } else { make.bottom.equalTo(self.view).offset(-findInPageHeight) } } // Setup the bottom toolbar toolbar?.snp.remakeConstraints { make in make.edges.equalTo(self.footer) make.height.equalTo(UIConstants.BottomToolbarHeight) } footer.snp.remakeConstraints { make in scrollController.footerBottomConstraint = make.bottom.equalTo(self.view.snp.bottom).constraint make.leading.trailing.equalTo(self.view) } urlBar.setNeedsUpdateConstraints() // Remake constraints even if we're already showing the home controller. // The home controller may change sizes if we tap the URL bar while on about:home. homePanelController?.view.snp.remakeConstraints { make in make.top.equalTo(self.urlBar.snp.bottom) make.left.right.equalTo(self.view) if self.homePanelIsInline { make.bottom.equalTo(self.toolbar?.snp.top ?? self.view.snp.bottom) } else { make.bottom.equalTo(self.view.snp.bottom) } } alertStackView.snp.remakeConstraints { make in make.centerX.equalTo(self.view) make.width.equalTo(self.view.snp.width) if let keyboardHeight = keyboardState?.intersectionHeightForView(self.view), keyboardHeight > 0 { make.bottom.equalTo(self.view).offset(-keyboardHeight) } else if let toolbar = self.toolbar { make.bottom.equalTo(toolbar.snp.top) } else { make.bottom.equalTo(self.view) } } } fileprivate func showHomePanelController(inline: Bool) { homePanelIsInline = inline if homePanelController == nil { let homePanelController = HomePanelViewController() homePanelController.profile = profile homePanelController.delegate = self homePanelController.url = tabManager.selectedTab?.url?.displayURL homePanelController.view.alpha = 0 self.homePanelController = homePanelController addChildViewController(homePanelController) view.addSubview(homePanelController.view) homePanelController.didMove(toParentViewController: self) } guard let homePanelController = self.homePanelController else { assertionFailure("homePanelController is still nil after assignment.") return } let isPrivate = tabManager.selectedTab?.isPrivate ?? false homePanelController.applyTheme(isPrivate ? Theme.Private : Theme.Normal) let panelNumber = tabManager.selectedTab?.url?.fragment // splitting this out to see if we can get better crash reports when this has a problem var newSelectedButtonIndex = 0 if let numberArray = panelNumber?.components(separatedBy: "=") { if let last = numberArray.last, let lastInt = Int(last) { newSelectedButtonIndex = lastInt } } homePanelController.selectedPanel = HomePanelType(rawValue: newSelectedButtonIndex) // We have to run this animation, even if the view is already showing because there may be a hide animation running // and we want to be sure to override its results. UIView.animate(withDuration: 0.2, animations: { () -> Void in homePanelController.view.alpha = 1 }, completion: { finished in if finished { self.webViewContainer.accessibilityElementsHidden = true UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } }) view.setNeedsUpdateConstraints() } fileprivate func hideHomePanelController() { if let controller = homePanelController { self.homePanelController = nil UIView.animate(withDuration: 0.2, delay: 0, options: .beginFromCurrentState, animations: { () -> Void in controller.view.alpha = 0 }, completion: { _ in controller.willMove(toParentViewController: nil) controller.view.removeFromSuperview() controller.removeFromParentViewController() self.webViewContainer.accessibilityElementsHidden = false UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // Refresh the reading view toolbar since the article record may have changed if let readerMode = self.tabManager.selectedTab?.getContentScript(name: ReaderMode.name()) as? ReaderMode, readerMode.state == .active { self.showReaderModeBar(animated: false) } }) } } fileprivate func updateInContentHomePanel(_ url: URL?) { if !urlBar.inOverlayMode { guard let url = url else { hideHomePanelController() return } if url.isAboutHomeURL { showHomePanelController(inline: true) } else if !url.isLocalUtility || url.isReaderModeURL { hideHomePanelController() } } } fileprivate func showSearchController() { if searchController != nil { return } let isPrivate = tabManager.selectedTab?.isPrivate ?? false searchController = SearchViewController(isPrivate: isPrivate) searchController!.searchEngines = profile.searchEngines searchController!.searchDelegate = self searchController!.profile = self.profile searchLoader = SearchLoader(profile: profile, urlBar: urlBar) searchLoader?.addListener(searchController!) addChildViewController(searchController!) view.addSubview(searchController!.view) searchController!.view.snp.makeConstraints { make in make.top.equalTo(self.urlBar.snp.bottom) make.left.right.bottom.equalTo(self.view) return } homePanelController?.view?.isHidden = true searchController!.didMove(toParentViewController: self) } fileprivate func hideSearchController() { if let searchController = searchController { searchController.willMove(toParentViewController: nil) searchController.view.removeFromSuperview() searchController.removeFromParentViewController() self.searchController = nil homePanelController?.view?.isHidden = false searchLoader = nil } } func finishEditingAndSubmit(_ url: URL, visitType: VisitType) { urlBar.currentURL = url urlBar.leaveOverlayMode() guard let tab = tabManager.selectedTab else { return } if let webView = tab.webView { resetSpoofedUserAgentIfRequired(webView, newURL: url) } if let nav = tab.loadRequest(PrivilegedRequest(url: url) as URLRequest) { self.recordNavigationInTab(tab, navigation: nav, visitType: visitType) } } func addBookmark(_ tabState: TabState) { guard let url = tabState.url else { return } let absoluteString = url.absoluteString let shareItem = ShareItem(url: absoluteString, title: tabState.title, favicon: tabState.favicon) _ = profile.bookmarks.shareItem(shareItem) var userData = [QuickActions.TabURLKey: shareItem.url] if let title = shareItem.title { userData[QuickActions.TabTitleKey] = title } QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark, withUserData: userData, toApplication: UIApplication.shared) } override func accessibilityPerformEscape() -> Bool { if urlBar.inOverlayMode { urlBar.SELdidClickCancel() return true } else if let selectedTab = tabManager.selectedTab, selectedTab.canGoBack { selectedTab.goBack() return true } return false } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { let webView = object as! WKWebView guard let kp = keyPath, let path = KVOConstants(rawValue: kp) else { assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")") return } switch path { case .estimatedProgress: guard webView == tabManager.selectedTab?.webView, let progress = change?[.newKey] as? Float else { break } if !(webView.url?.isLocalUtility ?? false) { urlBar.updateProgressBar(progress) } else { urlBar.hideProgressBar() } case .loading: guard let loading = change?[.newKey] as? Bool else { break } if webView == tabManager.selectedTab?.webView { navigationToolbar.updateReloadStatus(loading) } if !loading { runScriptsOnWebView(webView) } case .URL: guard let tab = tabManager[webView] else { break } // To prevent spoofing, only change the URL immediately if the new URL is on // the same origin as the current URL. Otherwise, do nothing and wait for // didCommitNavigation to confirm the page load. if tab.url?.origin == webView.url?.origin { tab.url = webView.url if tab === tabManager.selectedTab && !tab.restoring { updateUIForReaderHomeStateForTab(tab) } } case .title: guard let tab = tabManager[webView] else { break } // Ensure that the tab title *actually* changed to prevent repeated calls // to navigateInTab(tab:). guard let title = tab.title else { break } if !title.isEmpty && title != tab.lastTitle { navigateInTab(tab: tab) } case .canGoBack: guard webView == tabManager.selectedTab?.webView, let canGoBack = change?[.newKey] as? Bool else { break } navigationToolbar.updateBackStatus(canGoBack) case .canGoForward: guard webView == tabManager.selectedTab?.webView, let canGoForward = change?[.newKey] as? Bool else { break } navigationToolbar.updateForwardStatus(canGoForward) default: assertionFailure("Unhandled KVO key: \(keyPath ?? "nil")") } } fileprivate func runScriptsOnWebView(_ webView: WKWebView) { guard let url = webView.url, url.isWebPage(), !url.isLocal else { return } webView.evaluateJavaScript("__firefox__.metadata && __firefox__.metadata.extractMetadata()", completionHandler: nil) if #available(iOS 11, *) { if NoImageModeHelper.isActivated(profile.prefs) { webView.evaluateJavaScript("__firefox__.NoImageMode.setEnabled(true)", completionHandler: nil) } } } func updateUIForReaderHomeStateForTab(_ tab: Tab) { updateURLBarDisplayURL(tab) scrollController.showToolbars(animated: false) if let url = tab.url { if url.isReaderModeURL { showReaderModeBar(animated: false) NotificationCenter.default.addObserver(self, selector: #selector(SELDynamicFontChanged), name: .DynamicFontChanged, object: nil) } else { hideReaderModeBar(animated: false) NotificationCenter.default.removeObserver(self, name: .DynamicFontChanged, object: nil) } updateInContentHomePanel(url as URL) } } /// Updates the URL bar text and button states. /// Call this whenever the page URL changes. fileprivate func updateURLBarDisplayURL(_ tab: Tab) { urlBar.currentURL = tab.url?.displayURL let isPage = tab.url?.displayURL?.isWebPage() ?? false navigationToolbar.updatePageStatus(isPage) } // MARK: Opening New Tabs func switchToPrivacyMode(isPrivate: Bool ) { // applyTheme(isPrivate ? Theme.PrivateMode : Theme.NormalMode) let tabTrayController = self.tabTrayController ?? TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self) if tabTrayController.privateMode != isPrivate { tabTrayController.changePrivacyMode(isPrivate) } self.tabTrayController = tabTrayController } func switchToTabForURLOrOpen(_ url: URL, isPrivate: Bool = false, isPrivileged: Bool) { popToBVC() if let tab = tabManager.getTabForURL(url) { tabManager.selectTab(tab) } else { openURLInNewTab(url, isPrivate: isPrivate, isPrivileged: isPrivileged) } } func openURLInNewTab(_ url: URL?, isPrivate: Bool = false, isPrivileged: Bool) { if let selectedTab = tabManager.selectedTab { screenshotHelper.takeScreenshot(selectedTab) } let request: URLRequest? if let url = url { request = isPrivileged ? PrivilegedRequest(url: url) as URLRequest : URLRequest(url: url) } else { request = nil } switchToPrivacyMode(isPrivate: isPrivate) _ = tabManager.addTabAndSelect(request, isPrivate: isPrivate) if url == nil && NewTabAccessors.getNewTabPage(profile.prefs) == .blankPage { urlBar.tabLocationViewDidTapLocation(urlBar.locationView) } } func openBlankNewTab(focusLocationField: Bool, isPrivate: Bool = false) { popToBVC() openURLInNewTab(nil, isPrivate: isPrivate, isPrivileged: true) if focusLocationField { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(300)) { // Without a delay, the text field fails to become first responder self.urlBar.tabLocationViewDidTapLocation(self.urlBar.locationView) } } } fileprivate func popToBVC() { guard let currentViewController = navigationController?.topViewController else { return } currentViewController.dismiss(animated: true, completion: nil) if currentViewController != self { _ = self.navigationController?.popViewController(animated: true) } else if urlBar.inOverlayMode { urlBar.SELdidClickCancel() } } // MARK: User Agent Spoofing func resetSpoofedUserAgentIfRequired(_ webView: WKWebView, newURL: URL) { // Reset the UA when a different domain is being loaded if webView.url?.host != newURL.host { webView.customUserAgent = nil } } func restoreSpoofedUserAgentIfRequired(_ webView: WKWebView, newRequest: URLRequest) { // Restore any non-default UA from the request's header let ua = newRequest.value(forHTTPHeaderField: "User-Agent") webView.customUserAgent = ua != UserAgent.defaultUserAgent() ? ua : nil } fileprivate func presentActivityViewController(_ url: URL, tab: Tab? = nil, sourceView: UIView?, sourceRect: CGRect, arrowDirection: UIPopoverArrowDirection) { let helper = ShareExtensionHelper(url: url, tab: tab) let controller = helper.createActivityViewController({ [unowned self] completed, _ in // After dismissing, check to see if there were any prompts we queued up self.showQueuedAlertIfAvailable() // Usually the popover delegate would handle nil'ing out the references we have to it // on the BVC when displaying as a popover but the delegate method doesn't seem to be // invoked on iOS 10. See Bug 1297768 for additional details. self.displayedPopoverController = nil self.updateDisplayedPopoverProperties = nil }) if let popoverPresentationController = controller.popoverPresentationController { popoverPresentationController.sourceView = sourceView popoverPresentationController.sourceRect = sourceRect popoverPresentationController.permittedArrowDirections = arrowDirection popoverPresentationController.delegate = self } present(controller, animated: true, completion: nil) LeanPlumClient.shared.track(event: .userSharedWebpage) } func updateFindInPageVisibility(visible: Bool) { if visible { if findInPageBar == nil { let findInPageBar = FindInPageBar() self.findInPageBar = findInPageBar findInPageBar.delegate = self alertStackView.addArrangedSubview(findInPageBar) findInPageBar.snp.makeConstraints { make in make.height.equalTo(UIConstants.ToolbarHeight) make.leading.trailing.equalTo(alertStackView) } updateViewConstraints() // We make the find-in-page bar the first responder below, causing the keyboard delegates // to fire. This, in turn, will animate the Find in Page container since we use the same // delegate to slide the bar up and down with the keyboard. We don't want to animate the // constraints added above, however, so force a layout now to prevent these constraints // from being lumped in with the keyboard animation. findInPageBar.layoutIfNeeded() } self.findInPageBar?.becomeFirstResponder() } else if let findInPageBar = self.findInPageBar { findInPageBar.endEditing(true) guard let webView = tabManager.selectedTab?.webView else { return } webView.evaluateJavaScript("__firefox__.findDone()", completionHandler: nil) findInPageBar.removeFromSuperview() self.findInPageBar = nil updateViewConstraints() } } @objc fileprivate func openSettings() { assert(Thread.isMainThread, "Opening settings requires being invoked on the main thread") let settingsTableViewController = AppSettingsTableViewController() settingsTableViewController.profile = profile settingsTableViewController.tabManager = tabManager settingsTableViewController.settingsDelegate = self let controller = SettingsNavigationController(rootViewController: settingsTableViewController) controller.popoverDelegate = self controller.modalPresentationStyle = .formSheet self.present(controller, animated: true, completion: nil) } fileprivate func postLocationChangeNotificationForTab(_ tab: Tab, navigation: WKNavigation?) { let notificationCenter = NotificationCenter.default var info = [AnyHashable: Any]() info["url"] = tab.url?.displayURL info["title"] = tab.title if let visitType = self.getVisitTypeForTab(tab, navigation: navigation)?.rawValue { info["visitType"] = visitType } info["isPrivate"] = tab.isPrivate notificationCenter.post(name: .OnLocationChange, object: self, userInfo: info) } func navigateInTab(tab: Tab, to navigation: WKNavigation? = nil) { tabManager.expireSnackbars() guard let webView = tab.webView else { print("Cannot navigate in tab without a webView") return } if let url = webView.url, !url.isErrorPageURL && !url.isAboutHomeURL { tab.lastExecutedTime = Date.now() postLocationChangeNotificationForTab(tab, navigation: navigation) // Fire the readability check. This is here and not in the pageShow event handler in ReaderMode.js anymore // because that event wil not always fire due to unreliable page caching. This will either let us know that // the currently loaded page can be turned into reading mode or if the page already is in reading mode. We // ignore the result because we are being called back asynchronous when the readermode status changes. webView.evaluateJavaScript("\(ReaderModeNamespace).checkReadability()", completionHandler: nil) // Re-run additional scripts in webView to extract updated favicons and metadata. runScriptsOnWebView(webView) } if tab === tabManager.selectedTab { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) // must be followed by LayoutChanged, as ScreenChanged will make VoiceOver // cursor land on the correct initial element, but if not followed by LayoutChanged, // VoiceOver will sometimes be stuck on the element, not allowing user to move // forward/backward. Strange, but LayoutChanged fixes that. UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil) } else if let webView = tab.webView { // To Screenshot a tab that is hidden we must add the webView, // then wait enough time for the webview to render. view.insertSubview(webView, at: 0) DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) { self.screenshotHelper.takeScreenshot(tab) if webView.superview == self.view { webView.removeFromSuperview() } } } // Remember whether or not a desktop site was requested tab.desktopSite = webView.customUserAgent?.isEmpty == false } // MARK: open in helper utils func addViewForOpenInHelper(_ openInHelper: OpenInHelper) { guard let view = openInHelper.openInView else { return } webViewContainerToolbar.addSubview(view) webViewContainerToolbar.snp.updateConstraints { make in make.height.equalTo(OpenInViewUX.ViewHeight) } view.snp.makeConstraints { make in make.edges.equalTo(webViewContainerToolbar) } self.openInHelper = openInHelper } func removeOpenInView() { guard let _ = self.openInHelper else { return } webViewContainerToolbar.subviews.forEach { $0.removeFromSuperview() } webViewContainerToolbar.snp.updateConstraints { make in make.height.equalTo(0) } self.openInHelper = nil } } extension BrowserViewController: ClipboardBarDisplayHandlerDelegate { func shouldDisplay(clipboardBar bar: ButtonToast) { show(buttonToast: bar, duration: ClipboardBarToastUX.ToastDelay) } } extension BrowserViewController: QRCodeViewControllerDelegate { func didScanQRCodeWithURL(_ url: URL) { openBlankNewTab(focusLocationField: false) finishEditingAndSubmit(url, visitType: VisitType.typed) UnifiedTelemetry.recordEvent(category: .action, method: .scan, object: .qrCodeURL) } func didScanQRCodeWithText(_ text: String) { openBlankNewTab(focusLocationField: false) submitSearchText(text) UnifiedTelemetry.recordEvent(category: .action, method: .scan, object: .qrCodeText) } } extension BrowserViewController: SettingsDelegate { func settingsOpenURLInNewTab(_ url: URL) { self.openURLInNewTab(url, isPrivileged: false) } } extension BrowserViewController: PresentingModalViewControllerDelegate { func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) { self.dismiss(animated: animated, completion: nil) } } /** * History visit management. * TODO: this should be expanded to track various visit types; see Bug 1166084. */ extension BrowserViewController { func ignoreNavigationInTab(_ tab: Tab, navigation: WKNavigation) { self.ignoredNavigation.insert(navigation) } func recordNavigationInTab(_ tab: Tab, navigation: WKNavigation, visitType: VisitType) { self.typedNavigation[navigation] = visitType } /** * Untrack and do the right thing. */ func getVisitTypeForTab(_ tab: Tab, navigation: WKNavigation?) -> VisitType? { guard let navigation = navigation else { // See https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/Cocoa/NavigationState.mm#L390 return VisitType.link } if let _ = self.ignoredNavigation.remove(navigation) { return nil } return self.typedNavigation.removeValue(forKey: navigation) ?? VisitType.link } } extension BrowserViewController: URLBarDelegate { func showTabTray() { webViewContainerToolbar.isHidden = true updateFindInPageVisibility(visible: false) let tabTrayController = TabTrayController(tabManager: tabManager, profile: profile, tabTrayDelegate: self) if let tab = tabManager.selectedTab { screenshotHelper.takeScreenshot(tab) } navigationController?.pushViewController(tabTrayController, animated: true) self.tabTrayController = tabTrayController } func urlBarDidPressReload(_ urlBar: URLBarView) { tabManager.selectedTab?.reload() } func urlBarDidPressQRButton(_ urlBar: URLBarView) { let qrCodeViewController = QRCodeViewController() qrCodeViewController.qrCodeDelegate = self let controller = QRCodeNavigationController(rootViewController: qrCodeViewController) self.present(controller, animated: true, completion: nil) } func urlBarDidPressPageOptions(_ urlBar: URLBarView, from button: UIButton) { let actionMenuPresenter: (URL, Tab, UIView, UIPopoverArrowDirection) -> Void = { (url, tab, view, _) in self.presentActivityViewController(url, tab: tab, sourceView: view, sourceRect: view.bounds, arrowDirection: .up) } let findInPageAction = { self.updateFindInPageVisibility(visible: true) } let successCallback: (String) -> Void = { (successMessage) in SimpleToast().showAlertWithText(successMessage, bottomContainer: self.webViewContainer) } guard let tab = tabManager.selectedTab, let urlString = tab.url?.absoluteString else { return } fetchBookmarkStatus(for: urlString).uponQueue(.main) { let isBookmarked = $0.successValue ?? false let pageActions = self.getTabActions(tab: tab, buttonView: button, presentShareMenu: actionMenuPresenter, findInPage: findInPageAction, presentableVC: self, isBookmarked: isBookmarked, success: successCallback) self.presentSheetWith(actions: pageActions, on: self, from: button) } } func urlBarDidLongPressPageOptions(_ urlBar: URLBarView, from button: UIButton) { guard let tab = tabManager.selectedTab else { return } guard let url = tab.canonicalURL?.displayURL else { return } presentActivityViewController(url, tab: tab, sourceView: button, sourceRect: button.bounds, arrowDirection: .up) } func urlBarDidPressStop(_ urlBar: URLBarView) { tabManager.selectedTab?.stop() } func urlBarDidPressTabs(_ urlBar: URLBarView) { showTabTray() } func urlBarDidPressReaderMode(_ urlBar: URLBarView) { if let tab = tabManager.selectedTab { if let readerMode = tab.getContentScript(name: "ReaderMode") as? ReaderMode { switch readerMode.state { case .available: enableReaderMode() UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .readerModeOpenButton) LeanPlumClient.shared.track(event: .useReaderView) case .active: disableReaderMode() UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .readerModeCloseButton) case .unavailable: break } } } } func urlBarDidLongPressReaderMode(_ urlBar: URLBarView) -> Bool { guard let tab = tabManager.selectedTab, let url = tab.url?.displayURL, let result = profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name) else { UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading list", comment: "Accessibility message e.g. spoken by VoiceOver after adding current webpage to the Reading List failed.")) return false } switch result { case .success: UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Added page to Reading List", comment: "Accessibility message e.g. spoken by VoiceOver after the current page gets added to the Reading List using the Reader View button, e.g. by long-pressing it or by its accessibility custom action.")) // TODO: https://bugzilla.mozilla.org/show_bug.cgi?id=1158503 provide some form of 'this has been added' visual feedback? case .failure(let error): UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Could not add page to Reading List. Maybe it’s already there?", comment: "Accessibility message e.g. spoken by VoiceOver after the user wanted to add current page to the Reading List and this was not done, likely because it already was in the Reading List, but perhaps also because of real failures.")) print("readingList.createRecordWithURL(url: \"\(url.absoluteString)\", ...) failed with error: \(error)") } return true } func locationActionsForURLBar(_ urlBar: URLBarView) -> [AccessibleAction] { if UIPasteboard.general.string != nil { return [pasteGoAction, pasteAction, copyAddressAction] } else { return [copyAddressAction] } } func urlBarDisplayTextForURL(_ url: URL?) -> (String?, Bool) { // use the initial value for the URL so we can do proper pattern matching with search URLs var searchURL = self.tabManager.selectedTab?.currentInitialURL if searchURL?.isErrorPageURL ?? true { searchURL = url } if let query = profile.searchEngines.queryForSearchURL(searchURL as URL?) { return (query, true) } else { return (url?.absoluteString, false) } } func urlBarDidLongPressLocation(_ urlBar: URLBarView) { let longPressAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) for action in locationActionsForURLBar(urlBar) { longPressAlertController.addAction(action.alertAction(style: .default)) } let cancelAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: { (alert: UIAlertAction) -> Void in }) longPressAlertController.addAction(cancelAction) let setupPopover = { [unowned self] in if let popoverPresentationController = longPressAlertController.popoverPresentationController { popoverPresentationController.sourceView = urlBar popoverPresentationController.sourceRect = urlBar.frame popoverPresentationController.permittedArrowDirections = .any popoverPresentationController.delegate = self } } setupPopover() if longPressAlertController.popoverPresentationController != nil { displayedPopoverController = longPressAlertController updateDisplayedPopoverProperties = setupPopover } self.present(longPressAlertController, animated: true, completion: nil) } func urlBarDidPressScrollToTop(_ urlBar: URLBarView) { if let selectedTab = tabManager.selectedTab { // Only scroll to top if we are not showing the home view controller if homePanelController == nil { selectedTab.webView?.scrollView.setContentOffset(CGPoint.zero, animated: true) } } } func urlBarLocationAccessibilityActions(_ urlBar: URLBarView) -> [UIAccessibilityCustomAction]? { return locationActionsForURLBar(urlBar).map { $0.accessibilityCustomAction } } func urlBar(_ urlBar: URLBarView, didEnterText text: String) { if text.isEmpty { hideSearchController() } else { showSearchController() searchController?.searchQuery = text searchLoader?.query = text } } func urlBar(_ urlBar: URLBarView, didSubmitText text: String) { if let fixupURL = URIFixup.getURL(text) { // The user entered a URL, so use it. finishEditingAndSubmit(fixupURL, visitType: VisitType.typed) return } // We couldn't build a URL, so check for a matching search keyword. let trimmedText = text.trimmingCharacters(in: .whitespaces) guard let possibleKeywordQuerySeparatorSpace = trimmedText.index(of: " ") else { submitSearchText(text) return } let possibleKeyword = trimmedText.substring(to: possibleKeywordQuerySeparatorSpace) let possibleQuery = trimmedText.substring(from: trimmedText.index(after: possibleKeywordQuerySeparatorSpace)) profile.bookmarks.getURLForKeywordSearch(possibleKeyword).uponQueue(.main) { result in if var urlString = result.successValue, let escapedQuery = possibleQuery.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed), let range = urlString.range(of: "%s") { urlString.replaceSubrange(range, with: escapedQuery) if let url = URL(string: urlString) { self.finishEditingAndSubmit(url, visitType: VisitType.typed) return } } self.submitSearchText(text) } } fileprivate func submitSearchText(_ text: String) { let engine = profile.searchEngines.defaultEngine if let searchURL = engine.searchURLForQuery(text) { // We couldn't find a matching search keyword, so do a search query. Telemetry.default.recordSearch(location: .actionBar, searchEngine: engine.engineID ?? "other") finishEditingAndSubmit(searchURL, visitType: VisitType.typed) } else { // We still don't have a valid URL, so something is broken. Give up. print("Error handling URL entry: \"\(text)\".") assertionFailure("Couldn't generate search URL: \(text)") } } func urlBarDidEnterOverlayMode(_ urlBar: URLBarView) { guard let profile = profile as? BrowserProfile else { return } if .blankPage == NewTabAccessors.getNewTabPage(profile.prefs) { UIAccessibilityPostNotification(UIAccessibilityScreenChangedNotification, nil) } else { if let toast = clipboardBarDisplayHandler?.clipboardToast { toast.removeFromSuperview() } showHomePanelController(inline: false) } LeanPlumClient.shared.track(event: .interactWithURLBar) } func urlBarDidLeaveOverlayMode(_ urlBar: URLBarView) { hideSearchController() updateInContentHomePanel(tabManager.selectedTab?.url as URL?) } } extension BrowserViewController: TabToolbarDelegate, PhotonActionSheetProtocol { func tabToolbarDidPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goBack() } func tabToolbarDidLongPressBack(_ tabToolbar: TabToolbarProtocol, button: UIButton) { showBackForwardList() } func tabToolbarDidPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.reload() } func tabToolbarDidLongPressReload(_ tabToolbar: TabToolbarProtocol, button: UIButton) { guard let tab = tabManager.selectedTab, tab.webView?.url != nil && (tab.getContentScript(name: ReaderMode.name()) as? ReaderMode)?.state != .active else { return } let toggleActionTitle: String if tab.desktopSite { toggleActionTitle = NSLocalizedString("Request Mobile Site", comment: "Action Sheet Button for Requesting the Mobile Site") } else { toggleActionTitle = NSLocalizedString("Request Desktop Site", comment: "Action Sheet Button for Requesting the Desktop Site") } let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) controller.addAction(UIAlertAction(title: toggleActionTitle, style: .default, handler: { _ in tab.toggleDesktopSite() })) controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: nil)) if #available(iOS 11, *) { if let helper = tab.contentBlocker as? ContentBlockerHelper { let state = helper.userOverrideForTrackingProtection if state != .disallowUserOverride { let title = state == .forceDisabled ? Strings.TrackingProtectionReloadWith : Strings.TrackingProtectionReloadWithout controller.addAction(UIAlertAction(title: title, style: .default, handler: {_ in helper.overridePrefsAndReloadTab(enableTrackingProtection: state == .forceDisabled) })) } } } controller.popoverPresentationController?.sourceView = toolbar ?? urlBar controller.popoverPresentationController?.sourceRect = button.frame present(controller, animated: true, completion: nil) } func tabToolbarDidPressStop(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.stop() } func tabToolbarDidPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) { tabManager.selectedTab?.goForward() } func tabToolbarDidLongPressForward(_ tabToolbar: TabToolbarProtocol, button: UIButton) { showBackForwardList() } func tabToolbarDidPressMenu(_ tabToolbar: TabToolbarProtocol, button: UIButton) { // ensure that any keyboards or spinners are dismissed before presenting the menu UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil) var actions: [[PhotonActionSheetItem]] = [] actions.append(getHomePanelActions()) actions.append(getOtherPanelActions(vcDelegate: self)) // force a modal if the menu is being displayed in compact split screen let shouldSupress = !topTabsVisible && UIDevice.current.userInterfaceIdiom == .pad presentSheetWith(actions: actions, on: self, from: button, supressPopover: shouldSupress) } func tabToolbarDidPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) { showTabTray() } func tabToolbarDidLongPressTabs(_ tabToolbar: TabToolbarProtocol, button: UIButton) { let controller = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) controller.addAction(UIAlertAction(title: Strings.NewTabTitle, style: .default, handler: { _ in self.tabManager.addTabAndSelect(isPrivate: false) })) controller.addAction(UIAlertAction(title: Strings.NewPrivateTabTitle, style: .default, handler: { _ in self.tabManager.addTabAndSelect(isPrivate: true) })) controller.addAction(UIAlertAction(title: Strings.CloseTabTitle, style: .destructive, handler: { _ in if let tab = self.tabManager.selectedTab { self.tabManager.removeTab(tab) } })) controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "Label for Cancel button"), style: .cancel, handler: nil)) controller.popoverPresentationController?.sourceView = toolbar ?? urlBar controller.popoverPresentationController?.sourceRect = button.frame present(controller, animated: true, completion: nil) } func showBackForwardList() { if let backForwardList = tabManager.selectedTab?.webView?.backForwardList { let backForwardViewController = BackForwardListViewController(profile: profile, backForwardList: backForwardList) backForwardViewController.tabManager = tabManager backForwardViewController.bvc = self backForwardViewController.modalPresentationStyle = .overCurrentContext backForwardViewController.backForwardTransitionDelegate = BackForwardListAnimator() self.present(backForwardViewController, animated: true, completion: nil) } } } extension BrowserViewController: TabDelegate { func tab(_ tab: Tab, didCreateWebView webView: WKWebView) { webView.frame = webViewContainer.frame // Observers that live as long as the tab. Make sure these are all cleared in willDeleteWebView below! KVOs.forEach { webView.addObserver(self, forKeyPath: $0.rawValue, options: .new, context: nil) } webView.scrollView.addObserver(self.scrollController, forKeyPath: KVOConstants.contentSize.rawValue, options: .new, context: nil) webView.uiDelegate = self let formPostHelper = FormPostHelper(tab: tab) tab.addContentScript(formPostHelper, name: FormPostHelper.name()) let readerMode = ReaderMode(tab: tab) readerMode.delegate = self tab.addContentScript(readerMode, name: ReaderMode.name()) // only add the logins helper if the tab is not a private browsing tab if !tab.isPrivate { let logins = LoginsHelper(tab: tab, profile: profile) tab.addContentScript(logins, name: LoginsHelper.name()) } let contextMenuHelper = ContextMenuHelper(tab: tab) contextMenuHelper.delegate = self tab.addContentScript(contextMenuHelper, name: ContextMenuHelper.name()) let errorHelper = ErrorPageHelper() tab.addContentScript(errorHelper, name: ErrorPageHelper.name()) let sessionRestoreHelper = SessionRestoreHelper(tab: tab) sessionRestoreHelper.delegate = self tab.addContentScript(sessionRestoreHelper, name: SessionRestoreHelper.name()) let findInPageHelper = FindInPageHelper(tab: tab) findInPageHelper.delegate = self tab.addContentScript(findInPageHelper, name: FindInPageHelper.name()) let noImageModeHelper = NoImageModeHelper(tab: tab) tab.addContentScript(noImageModeHelper, name: NoImageModeHelper.name()) let printHelper = PrintHelper(tab: tab) tab.addContentScript(printHelper, name: PrintHelper.name()) let customSearchHelper = CustomSearchHelper(tab: tab) tab.addContentScript(customSearchHelper, name: CustomSearchHelper.name()) let nightModeHelper = NightModeHelper(tab: tab) tab.addContentScript(nightModeHelper, name: NightModeHelper.name()) // XXX: Bug 1390200 - Disable NSUserActivity/CoreSpotlight temporarily // let spotlightHelper = SpotlightHelper(tab: tab) // tab.addHelper(spotlightHelper, name: SpotlightHelper.name()) tab.addContentScript(LocalRequestHelper(), name: LocalRequestHelper.name()) let historyStateHelper = HistoryStateHelper(tab: tab) historyStateHelper.delegate = self tab.addContentScript(historyStateHelper, name: HistoryStateHelper.name()) if #available(iOS 11, *) { (tab.contentBlocker as? ContentBlockerHelper)?.setupForWebView() } let metadataHelper = MetadataParserHelper(tab: tab, profile: profile) tab.addContentScript(metadataHelper, name: MetadataParserHelper.name()) } func tab(_ tab: Tab, willDeleteWebView webView: WKWebView) { tab.cancelQueuedAlerts() KVOs.forEach { webView.removeObserver(self, forKeyPath: $0.rawValue) } webView.scrollView.removeObserver(self.scrollController, forKeyPath: KVOConstants.contentSize.rawValue) webView.uiDelegate = nil webView.scrollView.delegate = nil webView.removeFromSuperview() } fileprivate func findSnackbar(_ barToFind: SnackBar) -> Int? { let bars = alertStackView.arrangedSubviews for (index, bar) in bars.enumerated() where bar === barToFind { return index } return nil } func showBar(_ bar: SnackBar, animated: Bool) { view.layoutIfNeeded() UIView.animate(withDuration: animated ? 0.25 : 0, animations: { _ in self.alertStackView.insertArrangedSubview(bar, at: 0) self.view.layoutIfNeeded() }) } func removeBar(_ bar: SnackBar, animated: Bool) { UIView.animate(withDuration: animated ? 0.25 : 0, animations: { _ in bar.removeFromSuperview() }) } func removeAllBars() { alertStackView.arrangedSubviews.forEach { $0.removeFromSuperview() } } func tab(_ tab: Tab, didAddSnackbar bar: SnackBar) { showBar(bar, animated: true) } func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar) { removeBar(bar, animated: true) } func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String) { updateFindInPageVisibility(visible: true) findInPageBar?.text = selection } } extension BrowserViewController: HomePanelViewControllerDelegate { func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectURL url: URL, visitType: VisitType) { finishEditingAndSubmit(url, visitType: visitType) } func homePanelViewController(_ homePanelViewController: HomePanelViewController, didSelectPanel panel: Int) { if let url = tabManager.selectedTab?.url, url.isAboutHomeURL { tabManager.selectedTab?.webView?.evaluateJavaScript("history.replaceState({}, '', '#panel=\(panel)')", completionHandler: nil) } } func homePanelViewControllerDidRequestToCreateAccount(_ homePanelViewController: HomePanelViewController) { presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same } func homePanelViewControllerDidRequestToSignIn(_ homePanelViewController: HomePanelViewController) { presentSignInViewController() // TODO UX Right now the flow for sign in and create account is the same } func homePanelViewControllerDidRequestToOpenInNewTab(_ url: URL, isPrivate: Bool) { let tab = self.tabManager.addTab(PrivilegedRequest(url: url) as URLRequest, afterTab: self.tabManager.selectedTab, isPrivate: isPrivate) // If we are showing toptabs a user can just use the top tab bar // If in overlay mode switching doesnt correctly dismiss the homepanels guard !topTabsVisible, !self.urlBar.inOverlayMode else { return } // We're not showing the top tabs; show a toast to quick switch to the fresh new tab. let toast = ButtonToast(labelText: Strings.ContextMenuButtonToastNewTabOpenedLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in if buttonPressed { self.tabManager.selectTab(tab) } }) self.show(buttonToast: toast) } } extension BrowserViewController: SearchViewControllerDelegate { func searchViewController(_ searchViewController: SearchViewController, didSelectURL url: URL) { finishEditingAndSubmit(url, visitType: VisitType.typed) } func searchViewController(_ searchViewController: SearchViewController, didLongPressSuggestion suggestion: String) { self.urlBar.setLocation(suggestion, search: true) } func presentSearchSettingsController() { let settingsNavigationController = SearchSettingsTableViewController() settingsNavigationController.model = self.profile.searchEngines settingsNavigationController.profile = self.profile let navController = ModalSettingsNavigationController(rootViewController: settingsNavigationController) self.present(navController, animated: true, completion: nil) } } extension BrowserViewController: TabManagerDelegate { func tabManager(_ tabManager: TabManager, didSelectedTabChange selected: Tab?, previous: Tab?) { // Remove the old accessibilityLabel. Since this webview shouldn't be visible, it doesn't need it // and having multiple views with the same label confuses tests. if let wv = previous?.webView { removeOpenInView() wv.endEditing(true) wv.accessibilityLabel = nil wv.accessibilityElementsHidden = true wv.accessibilityIdentifier = nil wv.removeFromSuperview() } if let tab = selected, let webView = tab.webView { updateURLBarDisplayURL(tab) if tab.isPrivate != previous?.isPrivate { applyTheme(tab.isPrivate ? .Private : .Normal) } readerModeCache = tab.isPrivate ? MemoryReaderModeCache.sharedInstance : DiskReaderModeCache.sharedInstance if let privateModeButton = topTabsViewController?.privateModeButton, previous != nil && previous?.isPrivate != tab.isPrivate { privateModeButton.setSelected(tab.isPrivate, animated: true) } ReaderModeHandlers.readerModeCache = readerModeCache scrollController.tab = selected webViewContainer.addSubview(webView) webView.snp.makeConstraints { make in make.top.equalTo(webViewContainerToolbar.snp.bottom) make.left.right.bottom.equalTo(self.webViewContainer) } webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view") webView.accessibilityIdentifier = "contentView" webView.accessibilityElementsHidden = false if webView.url == nil { // The web view can go gray if it was zombified due to memory pressure. // When this happens, the URL is nil, so try restoring the page upon selection. tab.reload() } } if let selected = selected, let previous = previous, selected.isPrivate != previous.isPrivate { updateTabCountUsingTabManager(tabManager) } removeAllBars() if let bars = selected?.bars { for bar in bars { showBar(bar, animated: true) } } updateFindInPageVisibility(visible: false) navigationToolbar.updateReloadStatus(selected?.loading ?? false) navigationToolbar.updateBackStatus(selected?.canGoBack ?? false) navigationToolbar.updateForwardStatus(selected?.canGoForward ?? false) if !(selected?.webView?.url?.isLocalUtility ?? false) { self.urlBar.updateProgressBar(Float(selected?.estimatedProgress ?? 0)) } if let readerMode = selected?.getContentScript(name: ReaderMode.name()) as? ReaderMode { urlBar.updateReaderModeState(readerMode.state) if readerMode.state == .active { showReaderModeBar(animated: false) } else { hideReaderModeBar(animated: false) } } else { urlBar.updateReaderModeState(ReaderModeState.unavailable) } updateInContentHomePanel(selected?.url as URL?) } func tabManager(_ tabManager: TabManager, willAddTab tab: Tab) { } func tabManager(_ tabManager: TabManager, didAddTab tab: Tab) { // If we are restoring tabs then we update the count once at the end if !tabManager.isRestoring { updateTabCountUsingTabManager(tabManager) } tab.tabDelegate = self } func tabManager(_ tabManager: TabManager, willRemoveTab tab: Tab) { } func tabManager(_ tabManager: TabManager, didRemoveTab tab: Tab) { updateTabCountUsingTabManager(tabManager) // tabDelegate is a weak ref (and the tab's webView may not be destroyed yet) // so we don't expcitly unset it. if let url = tab.url, !url.isAboutURL && !tab.isPrivate { profile.recentlyClosedTabs.addTab(url as URL, title: tab.title, faviconURL: tab.displayFavicon?.url) } } func tabManagerDidAddTabs(_ tabManager: TabManager) { updateTabCountUsingTabManager(tabManager) } func tabManagerDidRestoreTabs(_ tabManager: TabManager) { updateTabCountUsingTabManager(tabManager) } func show(buttonToast: ButtonToast, afterWaiting delay: DispatchTimeInterval = SimpleToastUX.ToastDelayBefore, duration: DispatchTimeInterval = SimpleToastUX.ToastDismissAfter) { // If BVC isnt visible hold on to this toast until viewDidAppear if self.view.window == nil { self.pendingToast = buttonToast return } DispatchQueue.main.asyncAfter(deadline: .now() + delay) { self.view.addSubview(buttonToast) buttonToast.snp.makeConstraints { make in make.left.right.equalTo(self.view) make.bottom.equalTo(self.webViewContainer) } buttonToast.showToast(duration: duration) } } func tabManagerDidRemoveAllTabs(_ tabManager: TabManager, toast: ButtonToast?) { guard let toast = toast, !tabTrayController.privateMode else { return } show(buttonToast: toast, afterWaiting: ButtonToastUX.ToastDelay) } fileprivate func updateTabCountUsingTabManager(_ tabManager: TabManager, animated: Bool = true) { if let selectedTab = tabManager.selectedTab { let count = selectedTab.isPrivate ? tabManager.privateTabs.count : tabManager.normalTabs.count toolbar?.updateTabCount(count, animated: animated) urlBar.updateTabCount(count, animated: !urlBar.inOverlayMode) topTabsViewController?.updateTabCount(count, animated: animated) } } } /// List of schemes that are allowed to open a popup window private let SchemesAllowedToOpenPopups = ["http", "https", "javascript", "data"] extension BrowserViewController: WKUIDelegate { func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? { guard let parentTab = tabManager[webView] else { return nil } if !navigationAction.isAllowed { print("Denying unprivileged request: \(navigationAction.request)") return nil } if let currentTab = tabManager.selectedTab { screenshotHelper.takeScreenshot(currentTab) } let request: URLRequest if let formPostHelper = parentTab.getContentScript(name: "FormPostHelper") as? FormPostHelper { request = formPostHelper.urlRequestForNavigationAction(navigationAction) } else { request = navigationAction.request } // If the page uses window.open() or target="_blank", open the page in a new tab. let newTab = tabManager.addTab(request, configuration: configuration, afterTab: parentTab, isPrivate: parentTab.isPrivate) tabManager.selectTab(newTab) // If the page we just opened has a bad scheme, we return nil here so that JavaScript does not // get a reference to it which it can return from window.open() - this will end up as a // CFErrorHTTPBadURL being presented. guard let scheme = (navigationAction.request as NSURLRequest).url?.scheme?.lowercased(), SchemesAllowedToOpenPopups.contains(scheme) else { return nil } return newTab.webView } fileprivate func canDisplayJSAlertForWebView(_ webView: WKWebView) -> Bool { // Only display a JS Alert if we are selected and there isn't anything being shown return ((tabManager.selectedTab == nil ? false : tabManager.selectedTab!.webView == webView)) && (self.presentedViewController == nil) } func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let messageAlert = MessageAlert(message: message, frame: frame, completionHandler: completionHandler) if canDisplayJSAlertForWebView(webView) { present(messageAlert.alertController(), animated: true, completion: nil) } else if let promptingTab = tabManager[webView] { promptingTab.queueJavascriptAlertPrompt(messageAlert) } else { // This should never happen since an alert needs to come from a web view but just in case call the handler // since not calling it will result in a runtime exception. completionHandler() } } func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { let confirmAlert = ConfirmPanelAlert(message: message, frame: frame, completionHandler: completionHandler) if canDisplayJSAlertForWebView(webView) { present(confirmAlert.alertController(), animated: true, completion: nil) } else if let promptingTab = tabManager[webView] { promptingTab.queueJavascriptAlertPrompt(confirmAlert) } else { completionHandler(false) } } func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { let textInputAlert = TextInputAlert(message: prompt, frame: frame, completionHandler: completionHandler, defaultText: defaultText) if canDisplayJSAlertForWebView(webView) { present(textInputAlert.alertController(), animated: true, completion: nil) } else if let promptingTab = tabManager[webView] { promptingTab.queueJavascriptAlertPrompt(textInputAlert) } else { completionHandler(nil) } } /// Invoked when an error occurs while starting to load data for the main frame. func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { // Ignore the "Frame load interrupted" error that is triggered when we cancel a request // to open an external application and hand it over to UIApplication.openURL(). The result // will be that we switch to the external app, for example the app store, while keeping the // original web page in the tab instead of replacing it with an error page. let error = error as NSError if error.domain == "WebKitErrorDomain" && error.code == 102 { return } if checkIfWebContentProcessHasCrashed(webView, error: error as NSError) { return } if error.code == Int(CFNetworkErrors.cfurlErrorCancelled.rawValue) { if let tab = tabManager[webView], tab === tabManager.selectedTab { urlBar.currentURL = tab.url?.displayURL } return } if let url = error.userInfo[NSURLErrorFailingURLErrorKey] as? URL { ErrorPageHelper().showPage(error, forUrl: url, inWebView: webView) // If the local web server isn't working for some reason (Firefox cellular data is // disabled in settings, for example), we'll fail to load the session restore URL. // We rely on loading that page to get the restore callback to reset the restoring // flag, so if we fail to load that page, reset it here. if url.aboutComponent == "sessionrestore" { tabManager.tabs.filter { $0.webView == webView }.first?.restoring = false } } } fileprivate func checkIfWebContentProcessHasCrashed(_ webView: WKWebView, error: NSError) -> Bool { if error.code == WKError.webContentProcessTerminated.rawValue && error.domain == "WebKitErrorDomain" { print("WebContent process has crashed. Trying to reloadFromOrigin to restart it.") webView.reloadFromOrigin() return true } return false } func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) { let helperForURL = OpenIn.helperForResponse(navigationResponse.response) if navigationResponse.canShowMIMEType { if let openInHelper = helperForURL { addViewForOpenInHelper(openInHelper) } decisionHandler(WKNavigationResponsePolicy.allow) return } guard var openInHelper = helperForURL else { let error = NSError(domain: ErrorPageHelper.MozDomain, code: Int(ErrorPageHelper.MozErrorDownloadsNotEnabled), userInfo: [NSLocalizedDescriptionKey: Strings.UnableToDownloadError]) ErrorPageHelper().showPage(error, forUrl: navigationResponse.response.url!, inWebView: webView) return decisionHandler(WKNavigationResponsePolicy.allow) } openInHelper.openInView = openInHelper.openInView ?? navigationToolbar.menuButton openInHelper.open() decisionHandler(WKNavigationResponsePolicy.cancel) } func webViewDidClose(_ webView: WKWebView) { if let tab = tabManager[webView] { self.tabManager.removeTab(tab) } } } extension BrowserViewController: ReaderModeDelegate { func readerMode(_ readerMode: ReaderMode, didChangeReaderModeState state: ReaderModeState, forTab tab: Tab) { // If this reader mode availability state change is for the tab that we currently show, then update // the button. Otherwise do nothing and the button will be updated when the tab is made active. if tabManager.selectedTab === tab { urlBar.updateReaderModeState(state) } } func readerMode(_ readerMode: ReaderMode, didDisplayReaderizedContentForTab tab: Tab) { self.showReaderModeBar(animated: true) tab.showContent(true) } } // MARK: - UIPopoverPresentationControllerDelegate extension BrowserViewController: UIPopoverPresentationControllerDelegate { func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) { displayedPopoverController = nil updateDisplayedPopoverProperties = nil } } extension BrowserViewController: UIAdaptivePresentationControllerDelegate { // Returning None here makes sure that the Popover is actually presented as a Popover and // not as a full-screen modal, which is the default on compact device classes. func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } } // MARK: - ReaderModeStyleViewControllerDelegate extension BrowserViewController: ReaderModeStyleViewControllerDelegate { func readerModeStyleViewController(_ readerModeStyleViewController: ReaderModeStyleViewController, didConfigureStyle style: ReaderModeStyle) { // Persist the new style to the profile let encodedStyle: [String: Any] = style.encodeAsDictionary() profile.prefs.setObject(encodedStyle, forKey: ReaderModeProfileKeyStyle) // Change the reader mode style on all tabs that have reader mode active for tabIndex in 0..<tabManager.count { if let tab = tabManager[tabIndex] { if let readerMode = tab.getContentScript(name: "ReaderMode") as? ReaderMode { if readerMode.state == ReaderModeState.active { readerMode.style = style } } } } } } extension BrowserViewController { func updateReaderModeBar() { if let readerModeBar = readerModeBar { if let tab = self.tabManager.selectedTab, tab.isPrivate { readerModeBar.applyTheme(.Private) } else { readerModeBar.applyTheme(.Normal) } if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, let record = successValue { readerModeBar.unread = record.unread readerModeBar.added = true } else { readerModeBar.unread = true readerModeBar.added = false } } else { readerModeBar.unread = true readerModeBar.added = false } } } func showReaderModeBar(animated: Bool) { if self.readerModeBar == nil { let readerModeBar = ReaderModeBarView(frame: CGRect.zero) readerModeBar.delegate = self view.insertSubview(readerModeBar, belowSubview: header) self.readerModeBar = readerModeBar } updateReaderModeBar() self.updateViewConstraints() } func hideReaderModeBar(animated: Bool) { if let readerModeBar = self.readerModeBar { readerModeBar.removeFromSuperview() self.readerModeBar = nil self.updateViewConstraints() } } /// There are two ways we can enable reader mode. In the simplest case we open a URL to our internal reader mode /// and be done with it. In the more complicated case, reader mode was already open for this page and we simply /// navigated away from it. So we look to the left and right in the BackForwardList to see if a readerized version /// of the current page is there. And if so, we go there. func enableReaderMode() { guard let tab = tabManager.selectedTab, let webView = tab.webView else { return } let backList = webView.backForwardList.backList let forwardList = webView.backForwardList.forwardList guard let currentURL = webView.backForwardList.currentItem?.url, let readerModeURL = currentURL.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) else { return } if backList.count > 1 && backList.last?.url == readerModeURL { webView.go(to: backList.last!) } else if forwardList.count > 0 && forwardList.first?.url == readerModeURL { webView.go(to: forwardList.first!) } else { // Store the readability result in the cache and load it. This will later move to the ReadabilityHelper. webView.evaluateJavaScript("\(ReaderModeNamespace).readerize()", completionHandler: { (object, error) -> Void in if let readabilityResult = ReadabilityResult(object: object as AnyObject?) { do { try self.readerModeCache.put(currentURL, readabilityResult) } catch _ { } if let nav = webView.load(PrivilegedRequest(url: readerModeURL) as URLRequest) { self.ignoreNavigationInTab(tab, navigation: nav) } } }) } } /// Disabling reader mode can mean two things. In the simplest case we were opened from the reading list, which /// means that there is nothing in the BackForwardList except the internal url for the reader mode page. In that /// case we simply open a new page with the original url. In the more complicated page, the non-readerized version /// of the page is either to the left or right in the BackForwardList. If that is the case, we navigate there. func disableReaderMode() { if let tab = tabManager.selectedTab, let webView = tab.webView { let backList = webView.backForwardList.backList let forwardList = webView.backForwardList.forwardList if let currentURL = webView.backForwardList.currentItem?.url { if let originalURL = currentURL.decodeReaderModeURL { if backList.count > 1 && backList.last?.url == originalURL { webView.go(to: backList.last!) } else if forwardList.count > 0 && forwardList.first?.url == originalURL { webView.go(to: forwardList.first!) } else { if let nav = webView.load(URLRequest(url: originalURL)) { self.ignoreNavigationInTab(tab, navigation: nav) } } } } } } func SELDynamicFontChanged(_ notification: Notification) { guard notification.name == .DynamicFontChanged else { return } var readerModeStyle = DefaultReaderModeStyle if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) { if let style = ReaderModeStyle(dict: dict as [String: AnyObject]) { readerModeStyle = style } } readerModeStyle.fontSize = ReaderModeFontSize.defaultSize self.readerModeStyleViewController(ReaderModeStyleViewController(), didConfigureStyle: readerModeStyle) } } extension BrowserViewController: ReaderModeBarViewDelegate { func readerModeBar(_ readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType) { switch buttonType { case .settings: if let readerMode = tabManager.selectedTab?.getContentScript(name: "ReaderMode") as? ReaderMode, readerMode.state == ReaderModeState.active { var readerModeStyle = DefaultReaderModeStyle if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) { if let style = ReaderModeStyle(dict: dict as [String: AnyObject]) { readerModeStyle = style } } let readerModeStyleViewController = ReaderModeStyleViewController() readerModeStyleViewController.delegate = self readerModeStyleViewController.readerModeStyle = readerModeStyle readerModeStyleViewController.modalPresentationStyle = .popover let setupPopover = { [unowned self] in if let popoverPresentationController = readerModeStyleViewController.popoverPresentationController { popoverPresentationController.backgroundColor = UIColor.white popoverPresentationController.delegate = self popoverPresentationController.sourceView = readerModeBar popoverPresentationController.sourceRect = CGRect(x: readerModeBar.frame.width/2, y: UIConstants.ToolbarHeight, width: 1, height: 1) popoverPresentationController.permittedArrowDirections = .up } } setupPopover() if readerModeStyleViewController.popoverPresentationController != nil { displayedPopoverController = readerModeStyleViewController updateDisplayedPopoverProperties = setupPopover } self.present(readerModeStyleViewController, animated: true, completion: nil) } case .markAsRead: if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, let record = successValue { profile.readingList?.updateRecord(record, unread: false) // TODO Check result, can this fail? readerModeBar.unread = false } } case .markAsUnread: if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url) { if let successValue = result.successValue, let record = successValue { profile.readingList?.updateRecord(record, unread: true) // TODO Check result, can this fail? readerModeBar.unread = true } } case .addToReadingList: if let tab = tabManager.selectedTab, let rawURL = tab.url, rawURL.isReaderModeURL, let url = rawURL.decodeReaderModeURL { profile.readingList?.createRecordWithURL(url.absoluteString, title: tab.title ?? "", addedBy: UIDevice.current.name) // TODO Check result, can this fail? readerModeBar.added = true readerModeBar.unread = true } case .removeFromReadingList: if let url = self.tabManager.selectedTab?.url?.displayURL?.absoluteString, let result = profile.readingList?.getRecordWithURL(url), let successValue = result.successValue, let record = successValue { profile.readingList?.deleteRecord(record) // TODO Check result, can this fail? readerModeBar.added = false readerModeBar.unread = false } } } } extension BrowserViewController: IntroViewControllerDelegate { @discardableResult func presentIntroViewController(_ force: Bool = false, animated: Bool = true) -> Bool { if let deeplink = self.profile.prefs.stringForKey("AdjustDeeplinkKey"), let url = URL(string: deeplink) { self.launchFxAFromDeeplinkURL(url) return true } if force || profile.prefs.intForKey(PrefsKeys.IntroSeen) == nil { let introViewController = IntroViewController() introViewController.delegate = self // On iPad we present it modally in a controller if topTabsVisible { introViewController.preferredContentSize = CGSize(width: IntroUX.Width, height: IntroUX.Height) introViewController.modalPresentationStyle = .formSheet } present(introViewController, animated: animated) { // On first run (and forced) open up the homepage in the background. if let homePageURL = HomePageAccessors.getHomePage(self.profile.prefs), let tab = self.tabManager.selectedTab, DeviceInfo.hasConnectivity() { tab.loadRequest(URLRequest(url: homePageURL)) } } return true } return false } func launchFxAFromDeeplinkURL(_ url: URL) { self.profile.prefs.removeObjectForKey("AdjustDeeplinkKey") var query = url.getQuery() query["entrypoint"] = "adjust_deepklink_ios" let fxaParams: FxALaunchParams fxaParams = FxALaunchParams(query: query) self.presentSignInViewController(fxaParams) } func introViewControllerDidFinish(_ introViewController: IntroViewController, requestToLogin: Bool) { self.profile.prefs.setInt(1, forKey: PrefsKeys.IntroSeen) LeanPlumClient.shared.track(event: .dismissedOnboarding) introViewController.dismiss(animated: true) { finished in if self.navigationController?.viewControllers.count ?? 0 > 1 { _ = self.navigationController?.popToRootViewController(animated: true) } if requestToLogin { self.presentSignInViewController() } } } func presentSignInViewController(_ fxaOptions: FxALaunchParams? = nil) { // Show the settings page if we have already signed in. If we haven't then show the signin page let vcToPresent: UIViewController if profile.hasAccount() { let settingsTableViewController = AppSettingsTableViewController() settingsTableViewController.profile = profile settingsTableViewController.tabManager = tabManager vcToPresent = settingsTableViewController } else { let signInVC = FxAContentViewController(profile: profile, fxaOptions: fxaOptions) signInVC.delegate = self signInVC.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissSignInViewController)) vcToPresent = signInVC } let settingsNavigationController = SettingsNavigationController(rootViewController: vcToPresent) settingsNavigationController.modalPresentationStyle = .formSheet settingsNavigationController.navigationBar.isTranslucent = false self.present(settingsNavigationController, animated: true, completion: nil) } func dismissSignInViewController() { self.dismiss(animated: true, completion: nil) } } extension BrowserViewController: FxAContentViewControllerDelegate { func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, withFlags flags: FxALoginFlags) { if flags.verified { self.dismiss(animated: true, completion: nil) } } func contentViewControllerDidCancel(_ viewController: FxAContentViewController) { self.dismiss(animated: true, completion: nil) } } extension BrowserViewController: ContextMenuHelperDelegate { func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didLongPressElements elements: ContextMenuHelper.Elements, gestureRecognizer: UIGestureRecognizer) { // locationInView can return (0, 0) when the long press is triggered in an invalid page // state (e.g., long pressing a link before the document changes, then releasing after a // different page loads). let touchPoint = gestureRecognizer.location(in: view) guard touchPoint != CGPoint.zero else { return } let touchSize = CGSize(width: 0, height: 16) let actionSheetController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) var dialogTitle: String? if let url = elements.link, let currentTab = tabManager.selectedTab { dialogTitle = url.absoluteString let isPrivate = currentTab.isPrivate let addTab = { (rURL: URL, isPrivate: Bool) in let tab = self.tabManager.addTab(URLRequest(url: rURL as URL), afterTab: currentTab, isPrivate: isPrivate) LeanPlumClient.shared.track(event: .openedNewTab, withParameters: ["Source": "Long Press Context Menu" as AnyObject]) guard !self.topTabsVisible else { return } // We're not showing the top tabs; show a toast to quick switch to the fresh new tab. let toast = ButtonToast(labelText: Strings.ContextMenuButtonToastNewTabOpenedLabelText, buttonText: Strings.ContextMenuButtonToastNewTabOpenedButtonText, completion: { buttonPressed in if buttonPressed { self.tabManager.selectTab(tab) } }) self.show(buttonToast: toast) } if !isPrivate { let newTabTitle = NSLocalizedString("Open in New Tab", comment: "Context menu item for opening a link in a new tab") let openNewTabAction = UIAlertAction(title: newTabTitle, style: .default) { (action: UIAlertAction) in addTab(url, false) } actionSheetController.addAction(openNewTabAction) } let openNewPrivateTabTitle = NSLocalizedString("Open in New Private Tab", tableName: "PrivateBrowsing", comment: "Context menu option for opening a link in a new private tab") let openNewPrivateTabAction = UIAlertAction(title: openNewPrivateTabTitle, style: .default) { (action: UIAlertAction) in addTab(url, true) } actionSheetController.addAction(openNewPrivateTabAction) let copyTitle = NSLocalizedString("Copy Link", comment: "Context menu item for copying a link URL to the clipboard") let copyAction = UIAlertAction(title: copyTitle, style: .default) { (action: UIAlertAction) -> Void in UIPasteboard.general.url = url as URL } actionSheetController.addAction(copyAction) let shareTitle = NSLocalizedString("Share Link", comment: "Context menu item for sharing a link URL") let shareAction = UIAlertAction(title: shareTitle, style: .default) { _ in self.presentActivityViewController(url as URL, sourceView: self.view, sourceRect: CGRect(origin: touchPoint, size: touchSize), arrowDirection: .any) } actionSheetController.addAction(shareAction) } if let url = elements.image { if dialogTitle == nil { dialogTitle = url.absoluteString } let photoAuthorizeStatus = PHPhotoLibrary.authorizationStatus() let saveImageTitle = NSLocalizedString("Save Image", comment: "Context menu item for saving an image") let saveImageAction = UIAlertAction(title: saveImageTitle, style: .default) { (action: UIAlertAction) -> Void in if photoAuthorizeStatus == .authorized || photoAuthorizeStatus == .notDetermined { self.getImage(url as URL) { UIImageWriteToSavedPhotosAlbum($0, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil) } } else { let accessDenied = UIAlertController(title: NSLocalizedString("Firefox would like to access your Photos", comment: "See http://mzl.la/1G7uHo7"), message: NSLocalizedString("This allows you to save the image to your Camera Roll.", comment: "See http://mzl.la/1G7uHo7"), preferredStyle: .alert) let dismissAction = UIAlertAction(title: Strings.CancelString, style: .default, handler: nil) accessDenied.addAction(dismissAction) let settingsAction = UIAlertAction(title: NSLocalizedString("Open Settings", comment: "See http://mzl.la/1G7uHo7"), style: .default ) { (action: UIAlertAction!) -> Void in UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:]) } accessDenied.addAction(settingsAction) self.present(accessDenied, animated: true, completion: nil) } } actionSheetController.addAction(saveImageAction) let copyImageTitle = NSLocalizedString("Copy Image", comment: "Context menu item for copying an image to the clipboard") let copyAction = UIAlertAction(title: copyImageTitle, style: .default) { (action: UIAlertAction) -> Void in // put the actual image on the clipboard // do this asynchronously just in case we're in a low bandwidth situation let pasteboard = UIPasteboard.general pasteboard.url = url as URL let changeCount = pasteboard.changeCount let application = UIApplication.shared var taskId: UIBackgroundTaskIdentifier = 0 taskId = application.beginBackgroundTask (expirationHandler: { _ in application.endBackgroundTask(taskId) }) Alamofire.request(url).validate(statusCode: 200..<300).response { response in // Only set the image onto the pasteboard if the pasteboard hasn't changed since // fetching the image; otherwise, in low-bandwidth situations, // we might be overwriting something that the user has subsequently added. if changeCount == pasteboard.changeCount, let imageData = response.data, response.error == nil { pasteboard.addImageWithData(imageData, forURL: url) } application.endBackgroundTask(taskId) } } actionSheetController.addAction(copyAction) } // If we're showing an arrow popup, set the anchor to the long press location. if let popoverPresentationController = actionSheetController.popoverPresentationController { popoverPresentationController.sourceView = view popoverPresentationController.sourceRect = CGRect(origin: touchPoint, size: touchSize) popoverPresentationController.permittedArrowDirections = .any popoverPresentationController.delegate = self } if actionSheetController.popoverPresentationController != nil { displayedPopoverController = actionSheetController } actionSheetController.title = dialogTitle?.ellipsize(maxLength: ActionSheetTitleMaxLength) let cancelAction = UIAlertAction(title: Strings.CancelString, style: UIAlertActionStyle.cancel, handler: nil) actionSheetController.addAction(cancelAction) self.present(actionSheetController, animated: true, completion: nil) } fileprivate func getImage(_ url: URL, success: @escaping (UIImage) -> Void) { Alamofire.request(url).validate(statusCode: 200..<300).response { response in if let data = response.data, let image = data.isGIF ? UIImage.imageFromGIFDataThreadSafe(data) : UIImage.imageFromDataThreadSafe(data) { success(image) } } } func contextMenuHelper(_ contextMenuHelper: ContextMenuHelper, didCancelGestureRecognizer: UIGestureRecognizer) { displayedPopoverController?.dismiss(animated: true) { self.displayedPopoverController = nil } } } extension BrowserViewController { func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) { if error == nil { LeanPlumClient.shared.track(event: .saveImage) } } } extension BrowserViewController: HistoryStateHelperDelegate { func historyStateHelper(_ historyStateHelper: HistoryStateHelper, didPushOrReplaceStateInTab tab: Tab) { navigateInTab(tab: tab) tabManager.storeChanges() } } /** A third party search engine Browser extension **/ extension BrowserViewController { func addCustomSearchButtonToWebView(_ webView: WKWebView) { //check if the search engine has already been added. let domain = webView.url?.domainURL.host let matches = self.profile.searchEngines.orderedEngines.filter {$0.shortName == domain} if !matches.isEmpty { self.customSearchEngineButton.tintColor = UIColor.gray self.customSearchEngineButton.isUserInteractionEnabled = false } else { self.customSearchEngineButton.tintColor = UIConstants.SystemBlueColor self.customSearchEngineButton.isUserInteractionEnabled = true } /* This is how we access hidden views in the WKContentView Using the public headers we can find the keyboard accessoryView which is not usually available. Specific values here are from the WKContentView headers. https://github.com/JaviSoto/iOS9-Runtime-Headers/blob/master/Frameworks/WebKit.framework/WKContentView.h */ guard let webContentView = UIView.findSubViewWithFirstResponder(webView) else { /* In some cases the URL bar can trigger the keyboard notification. In that case the webview isnt the first responder and a search button should not be added. */ return } guard let input = webContentView.perform(#selector(getter: UIResponder.inputAccessoryView)), let inputView = input.takeUnretainedValue() as? UIInputView, let nextButton = inputView.value(forKey: "_nextItem") as? UIBarButtonItem, let nextButtonView = nextButton.value(forKey: "view") as? UIView else { //failed to find the inputView instead lets use the inputAssistant addCustomSearchButtonToInputAssistant(webContentView) return } inputView.addSubview(self.customSearchEngineButton) self.customSearchEngineButton.snp.remakeConstraints { make in make.leading.equalTo(nextButtonView.snp.trailing).offset(20) make.width.equalTo(inputView.snp.height) make.top.equalTo(nextButtonView.snp.top) make.height.equalTo(inputView.snp.height) } } /** This adds the customSearchButton to the inputAssistant for cases where the inputAccessoryView could not be found for example on the iPad where it does not exist. However this only works on iOS9 **/ func addCustomSearchButtonToInputAssistant(_ webContentView: UIView) { guard customSearchBarButton == nil else { return //The searchButton is already on the keyboard } let inputAssistant = webContentView.inputAssistantItem let item = UIBarButtonItem(customView: customSearchEngineButton) customSearchBarButton = item _ = Try(withTry: { inputAssistant.trailingBarButtonGroups.last?.barButtonItems.append(item) }) { (exception) in Sentry.shared.send(message: "Failed adding custom search button to input assistant", tag: .general, severity: .error, description: "\(exception ??? "nil")") } } func addCustomSearchEngineForFocusedElement() { guard let webView = tabManager.selectedTab?.webView else { return } webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in guard let searchQuery = result as? String, let favicon = self.tabManager.selectedTab!.displayFavicon else { //Javascript responded with an incorrectly formatted message. Show an error. let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } self.addSearchEngine(searchQuery, favicon: favicon) self.customSearchEngineButton.tintColor = UIColor.gray self.customSearchEngineButton.isUserInteractionEnabled = false } } func addSearchEngine(_ searchQuery: String, favicon: Favicon) { guard searchQuery != "", let iconURL = URL(string: favicon.url), let url = URL(string: searchQuery.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)!), let shortName = url.domainURL.host else { let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } let alert = ThirdPartySearchAlerts.addThirdPartySearchEngine { alert in self.customSearchEngineButton.tintColor = UIColor.gray self.customSearchEngineButton.isUserInteractionEnabled = false SDWebImageManager.shared().loadImage(with: iconURL, options: .continueInBackground, progress: nil) { (image, _, _, _, _, _) in guard let image = image else { let alert = ThirdPartySearchAlerts.failedToAddThirdPartySearch() self.present(alert, animated: true, completion: nil) return } self.profile.searchEngines.addSearchEngine(OpenSearchEngine(engineID: nil, shortName: shortName, image: image, searchTemplate: searchQuery, suggestTemplate: nil, isCustomEngine: true)) let Toast = SimpleToast() Toast.showAlertWithText(Strings.ThirdPartySearchEngineAdded, bottomContainer: self.webViewContainer) } } self.present(alert, animated: true, completion: {}) } } extension BrowserViewController: KeyboardHelperDelegate { func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { keyboardState = state updateViewConstraints() UIView.animate(withDuration: state.animationDuration) { UIView.setAnimationCurve(state.animationCurve) self.alertStackView.layoutIfNeeded() } guard let webView = tabManager.selectedTab?.webView else { return } webView.evaluateJavaScript("__firefox__.searchQueryForField()") { (result, _) in guard let _ = result as? String else { return } self.addCustomSearchButtonToWebView(webView) } } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) { } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { keyboardState = nil updateViewConstraints() //If the searchEngineButton exists remove it form the keyboard if let buttonGroup = customSearchBarButton?.buttonGroup { buttonGroup.barButtonItems = buttonGroup.barButtonItems.filter { $0 != customSearchBarButton } customSearchBarButton = nil } if self.customSearchEngineButton.superview != nil { self.customSearchEngineButton.removeFromSuperview() } UIView.animate(withDuration: state.animationDuration) { UIView.setAnimationCurve(state.animationCurve) self.alertStackView.layoutIfNeeded() } } } extension BrowserViewController: SessionRestoreHelperDelegate { func sessionRestoreHelper(_ helper: SessionRestoreHelper, didRestoreSessionForTab tab: Tab) { tab.restoring = false if let tab = tabManager.selectedTab, tab.webView === tab.webView { updateUIForReaderHomeStateForTab(tab) } } } extension BrowserViewController: TabTrayDelegate { // This function animates and resets the tab chrome transforms when // the tab tray dismisses. func tabTrayDidDismiss(_ tabTray: TabTrayController) { resetBrowserChrome() } func tabTrayDidAddBookmark(_ tab: Tab) { guard let url = tab.url?.absoluteString, !url.isEmpty else { return } self.addBookmark(tab.tabState) } func tabTrayDidAddToReadingList(_ tab: Tab) -> ReadingListClientRecord? { guard let url = tab.url?.absoluteString, !url.isEmpty else { return nil } return profile.readingList?.createRecordWithURL(url, title: tab.title ?? url, addedBy: UIDevice.current.name).successValue } func tabTrayRequestsPresentationOf(_ viewController: UIViewController) { self.present(viewController, animated: false, completion: nil) } } // MARK: Browser Chrome Theming extension BrowserViewController: Themeable { func applyTheme(_ theme: Theme) { let ui: [Themeable?] = [urlBar, toolbar, readerModeBar, topTabsViewController] ui.forEach { $0?.applyTheme(theme) } statusBarOverlay.backgroundColor = shouldShowTopTabsForTraitCollection(traitCollection) ? UIColor.Defaults.Grey80 : urlBar.backgroundColor setNeedsStatusBarAppearanceUpdate() } } extension BrowserViewController: FindInPageBarDelegate, FindInPageHelperDelegate { func findInPage(_ findInPage: FindInPageBar, didTextChange text: String) { find(text, function: "find") } func findInPage(_ findInPage: FindInPageBar, didFindNextWithText text: String) { findInPageBar?.endEditing(true) find(text, function: "findNext") } func findInPage(_ findInPage: FindInPageBar, didFindPreviousWithText text: String) { findInPageBar?.endEditing(true) find(text, function: "findPrevious") } func findInPageDidPressClose(_ findInPage: FindInPageBar) { updateFindInPageVisibility(visible: false) } fileprivate func find(_ text: String, function: String) { guard let webView = tabManager.selectedTab?.webView else { return } let escaped = text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") webView.evaluateJavaScript("__firefox__.\(function)(\"\(escaped)\")", completionHandler: nil) } func findInPageHelper(_ findInPageHelper: FindInPageHelper, didUpdateCurrentResult currentResult: Int) { findInPageBar?.currentResult = currentResult } func findInPageHelper(_ findInPageHelper: FindInPageHelper, didUpdateTotalResults totalResults: Int) { findInPageBar?.totalResults = totalResults } } extension BrowserViewController: JSPromptAlertControllerDelegate { func promptAlertControllerDidDismiss(_ alertController: JSPromptAlertController) { showQueuedAlertIfAvailable() } } extension BrowserViewController: TopTabsDelegate { func topTabsDidPressTabs() { urlBar.leaveOverlayMode(didCancel: true) self.urlBarDidPressTabs(urlBar) } func topTabsDidPressNewTab(_ isPrivate: Bool) { openBlankNewTab(focusLocationField: false, isPrivate: isPrivate) } func topTabsDidTogglePrivateMode() { guard let _ = tabManager.selectedTab else { return } urlBar.leaveOverlayMode() } func topTabsDidChangeTab() { urlBar.leaveOverlayMode(didCancel: true) } } extension BrowserViewController: ClientPickerViewControllerDelegate, InstructionsViewControllerDelegate { func instructionsViewControllerDidClose(_ instructionsViewController: InstructionsViewController) { self.popToBVC() } func clientPickerViewControllerDidCancel(_ clientPickerViewController: ClientPickerViewController) { self.popToBVC() } func clientPickerViewController(_ clientPickerViewController: ClientPickerViewController, didPickClients clients: [RemoteClient]) { guard let tab = tabManager.selectedTab, let url = tab.canonicalURL?.displayURL?.absoluteString else { return } let shareItem = ShareItem(url: url, title: tab.title, favicon: tab.displayFavicon) guard shareItem.isShareable else { let alert = UIAlertController(title: Strings.SendToErrorTitle, message: Strings.SendToErrorMessage, preferredStyle: .alert) alert.addAction(UIAlertAction(title: Strings.SendToErrorOKButton, style: .default) { _ in self.popToBVC()}) present(alert, animated: true, completion: nil) return } profile.sendItems([shareItem], toClients: clients).uponQueue(.main) { _ in self.popToBVC() } } }
mpl-2.0
b3b62500487c1cc25a73a82e95849694
43.463681
406
0.661441
5.893027
false
false
false
false
swiftix/swift
test/SILGen/objc_protocols.swift
1
13392
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -disable-objc-attr-requires-foundation-module | %FileCheck %s // REQUIRES: objc_interop import gizmo import objc_protocols_Bas @objc protocol NSRuncing { func runce() -> NSObject func copyRuncing() -> NSObject func foo() static func mince() -> NSObject } @objc protocol NSFunging { func funge() func foo() } protocol Ansible { func anse() } // CHECK-LABEL: sil hidden @_T014objc_protocols0A8_generic{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[THIS:%.*]] : $T): // -- Result of runce is autoreleased according to default objc conv // CHECK: [[METHOD:%.*]] = witness_method [volatile] {{\$.*}}, #NSRuncing.runce!1.foreign // CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<T>([[BORROWED_THIS:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @autoreleased NSObject // CHECK: end_borrow [[BORROWED_THIS]] from [[THIS]] // -- Result of copyRuncing is received copy_valued according to -copy family // CHECK: [[METHOD:%.*]] = witness_method [volatile] {{\$.*}}, #NSRuncing.copyRuncing!1.foreign // CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]] // CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<T>([[BORROWED_THIS:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @owned NSObject // CHECK: end_borrow [[BORROWED_THIS]] from [[THIS]] // -- Arguments are not consumed by objc calls // CHECK: destroy_value [[THIS]] func objc_generic<T : NSRuncing>(_ x: T) -> (NSObject, NSObject) { return (x.runce(), x.copyRuncing()) } // CHECK-LABEL: sil hidden @_T014objc_protocols0A22_generic_partial_applyyxAA9NSRuncingRzlF : $@convention(thin) <T where T : NSRuncing> (@owned T) -> () { func objc_generic_partial_apply<T : NSRuncing>(_ x: T) { // CHECK: bb0([[ARG:%.*]] : $T): // CHECK: [[FN:%.*]] = function_ref @[[THUNK1:_T014objc_protocols9NSRuncingP5runceSo8NSObjectCyFTcTO]] : // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[METHOD:%.*]] = apply [[FN]]<T>([[ARG_COPY]]) // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[METHOD]] _ = x.runce // CHECK: [[FN:%.*]] = function_ref @[[THUNK1]] : // CHECK: [[METHOD:%.*]] = partial_apply [[FN]]<T>() // CHECK: destroy_value [[METHOD]] _ = T.runce // CHECK: [[FN:%.*]] = function_ref @[[THUNK2:_T014objc_protocols9NSRuncingP5minceSo8NSObjectCyFZTcTO]] // CHECK: [[METATYPE:%.*]] = metatype $@thick T.Type // CHECK: [[METHOD:%.*]] = apply [[FN]]<T>([[METATYPE]]) // CHECK: destroy_value [[METHOD:%.*]] _ = T.mince // CHECK: destroy_value [[ARG]] } // CHECK: } // end sil function '_T014objc_protocols0A22_generic_partial_applyyxAA9NSRuncingRzlF' // CHECK: sil shared [serializable] [thunk] @[[THUNK1]] : // CHECK: bb0([[SELF:%.*]] : $Self): // CHECK: [[FN:%.*]] = function_ref @[[THUNK1_THUNK:_T014objc_protocols9NSRuncingP5runceSo8NSObjectCyFTO]] : // CHECK: [[METHOD:%.*]] = partial_apply [[FN]]<Self>([[SELF]]) // CHECK: return [[METHOD]] // CHECK: } // end sil function '[[THUNK1]]' // CHECK: sil shared [serializable] [thunk] @[[THUNK1_THUNK]] // CHECK: bb0([[SELF:%.*]] : $Self): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[FN:%.*]] = witness_method $Self, #NSRuncing.runce!1.foreign // CHECK: [[RESULT:%.*]] = apply [[FN]]<Self>([[SELF_COPY]]) // CHECK: destroy_value [[SELF_COPY]] // CHECK: return [[RESULT]] // CHECK: } // end sil function '[[THUNK1_THUNK]]' // CHECK: sil shared [serializable] [thunk] @[[THUNK2]] : // CHECK: [[FN:%.*]] = function_ref @[[THUNK2_THUNK:_T014objc_protocols9NSRuncingP5minceSo8NSObjectCyFZTO]] // CHECK: [[METHOD:%.*]] = partial_apply [[FN]]<Self>(%0) // CHECK: return [[METHOD]] // CHECK: } // end sil function '[[THUNK2]]' // CHECK: sil shared [serializable] [thunk] @[[THUNK2_THUNK]] : // CHECK: [[FN:%.*]] = witness_method $Self, #NSRuncing.mince!1.foreign // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Self>(%0) // CHECK-NEXT: return [[RESULT]] // CHECK: } // end sil function '[[THUNK2_THUNK]]' // CHECK-LABEL: sil hidden @_T014objc_protocols0A9_protocol{{[_0-9a-zA-Z]*}}F // CHECK: bb0([[THIS:%.*]] : $NSRuncing): // -- Result of runce is autoreleased according to default objc conv // CHECK: [[BORROWED_THIS_1:%.*]] = begin_borrow [[THIS]] // CHECK: [[THIS1:%.*]] = open_existential_ref [[BORROWED_THIS_1]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSRuncing.runce!1.foreign // CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<[[OPENED]]>([[THIS1]]) // -- Result of copyRuncing is received copy_valued according to -copy family // CHECK: [[BORROWED_THIS_2:%.*]] = begin_borrow [[THIS]] // CHECK: [[THIS2:%.*]] = open_existential_ref [[BORROWED_THIS_2]] : $NSRuncing to $[[OPENED2:@opened(.*) NSRuncing]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED2]], #NSRuncing.copyRuncing!1.foreign // CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<[[OPENED2]]>([[THIS2:%.*]]) // -- Arguments are not consumed by objc calls // CHECK: end_borrow [[BORROWED_THIS_2]] from [[THIS]] // CHECK: end_borrow [[BORROWED_THIS_1]] from [[THIS]] // CHECK: destroy_value [[THIS]] func objc_protocol(_ x: NSRuncing) -> (NSObject, NSObject) { return (x.runce(), x.copyRuncing()) } // CHECK-LABEL: sil hidden @_T014objc_protocols0A23_protocol_partial_applyyAA9NSRuncing_pF : $@convention(thin) (@owned NSRuncing) -> () { func objc_protocol_partial_apply(_ x: NSRuncing) { // CHECK: bb0([[ARG:%.*]] : $NSRuncing): // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[OPENED_ARG:%.*]] = open_existential_ref [[BORROWED_ARG]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]] // CHECK: [[FN:%.*]] = function_ref @_T014objc_protocols9NSRuncingP5runceSo8NSObjectCyFTcTO // CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]] // CHECK: [[RESULT:%.*]] = apply [[FN]]<[[OPENED]]>([[OPENED_ARG_COPY]]) // CHECK: destroy_value [[RESULT]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] _ = x.runce // FIXME: rdar://21289579 // _ = NSRuncing.runce } // CHECK : } // end sil function '_T014objc_protocols0A23_protocol_partial_applyyAA9NSRuncing_pF' // CHECK-LABEL: sil hidden @_T014objc_protocols0A21_protocol_composition{{[_0-9a-zA-Z]*}}F func objc_protocol_composition(_ x: NSRuncing & NSFunging) { // CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $NSFunging & NSRuncing to $[[OPENED:@opened(.*) NSFunging & NSRuncing]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSRuncing.runce!1.foreign // CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]]) x.runce() // CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $NSFunging & NSRuncing to $[[OPENED:@opened(.*) NSFunging & NSRuncing]] // CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSFunging.funge!1.foreign // CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]]) x.funge() } // -- ObjC thunks get emitted for ObjC protocol conformances class Foo : NSRuncing, NSFunging, Ansible { // -- NSRuncing @objc func runce() -> NSObject { return NSObject() } @objc func copyRuncing() -> NSObject { return NSObject() } @objc static func mince() -> NSObject { return NSObject() } // -- NSFunging @objc func funge() {} // -- Both NSRuncing and NSFunging @objc func foo() {} // -- Ansible func anse() {} } // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC5runce{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC11copyRuncing{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC5funge{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC3foo{{[_0-9a-zA-Z]*}}FTo // CHECK-NOT: sil hidden @_TToF{{.*}}anse{{.*}} class Bar { } extension Bar : NSRuncing { @objc func runce() -> NSObject { return NSObject() } @objc func copyRuncing() -> NSObject { return NSObject() } @objc func foo() {} @objc static func mince() -> NSObject { return NSObject() } } // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3BarC5runce{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3BarC11copyRuncing{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3BarC3foo{{[_0-9a-zA-Z]*}}FTo // class Bas from objc_protocols_Bas module extension Bas : NSRuncing { // runce() implementation from the original definition of Bas @objc func copyRuncing() -> NSObject { return NSObject() } @objc func foo() {} @objc static func mince() -> NSObject { return NSObject() } } // CHECK-LABEL: sil hidden [thunk] @_T018objc_protocols_Bas0C0C0a1_B0E11copyRuncing{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @_T018objc_protocols_Bas0C0C0a1_B0E3foo{{[_0-9a-zA-Z]*}}FTo // -- Inherited objc protocols protocol Fungible : NSFunging { } class Zim : Fungible { @objc func funge() {} @objc func foo() {} } // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3ZimC5funge{{[_0-9a-zA-Z]*}}FTo // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3ZimC3foo{{[_0-9a-zA-Z]*}}FTo // class Zang from objc_protocols_Bas module extension Zang : Fungible { // funge() implementation from the original definition of Zim @objc func foo() {} } // CHECK-LABEL: sil hidden [thunk] @_T018objc_protocols_Bas4ZangC0a1_B0E3foo{{[_0-9a-zA-Z]*}}FTo // -- objc protocols with property requirements in extensions // <rdar://problem/16284574> @objc protocol NSCounting { var count: Int {get} } class StoredPropertyCount { @objc let count = 0 } extension StoredPropertyCount: NSCounting {} // CHECK-LABEL: sil hidden [transparent] [thunk] @_T014objc_protocols19StoredPropertyCountC5countSivgTo class ComputedPropertyCount { @objc var count: Int { return 0 } } extension ComputedPropertyCount: NSCounting {} // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols21ComputedPropertyCountC5countSivgTo // -- adding @objc protocol conformances to native ObjC classes should not // emit thunks since the methods are already available to ObjC. // Gizmo declared in Inputs/usr/include/Gizmo.h extension Gizmo : NSFunging { } // CHECK-NOT: _TTo{{.*}}5Gizmo{{.*}} @objc class InformallyFunging { @objc func funge() {} @objc func foo() {} } extension InformallyFunging: NSFunging { } @objc protocol Initializable { init(int: Int) } // CHECK-LABEL: sil hidden @_T014objc_protocols28testInitializableExistentialAA0D0_pAaC_pXp_Si1itF : $@convention(thin) (@thick Initializable.Type, Int) -> @owned Initializable { func testInitializableExistential(_ im: Initializable.Type, i: Int) -> Initializable { // CHECK: bb0([[META:%[0-9]+]] : $@thick Initializable.Type, [[I:%[0-9]+]] : $Int): // CHECK: [[I2_BOX:%[0-9]+]] = alloc_box ${ var Initializable } // CHECK: [[PB:%.*]] = project_box [[I2_BOX]] // CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[META]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type // CHECK: [[ARCHETYPE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[ARCHETYPE_META]] : $@thick (@opened([[N]]) Initializable).Type to $@objc_metatype (@opened([[N]]) Initializable).Type // CHECK: [[I2_ALLOC:%[0-9]+]] = alloc_ref_dynamic [objc] [[ARCHETYPE_META_OBJC]] : $@objc_metatype (@opened([[N]]) Initializable).Type, $@opened([[N]]) Initializable // CHECK: [[INIT_WITNESS:%[0-9]+]] = witness_method [volatile] $@opened([[N]]) Initializable, #Initializable.init!initializer.1.foreign : {{.*}}, [[ARCHETYPE_META]]{{.*}} : $@convention(objc_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @owned τ_0_0) -> @owned τ_0_0 // CHECK: [[I2:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[I]], [[I2_ALLOC]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @owned τ_0_0) -> @owned τ_0_0 // CHECK: [[I2_EXIST_CONTAINER:%[0-9]+]] = init_existential_ref [[I2]] : $@opened([[N]]) Initializable : $@opened([[N]]) Initializable, $Initializable // CHECK: store [[I2_EXIST_CONTAINER]] to [init] [[PB]] : $*Initializable // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*Initializable // CHECK: [[I2:%[0-9]+]] = load [copy] [[READ]] : $*Initializable // CHECK: destroy_value [[I2_BOX]] : ${ var Initializable } // CHECK: return [[I2]] : $Initializable var i2 = im.init(int: i) return i2 } // CHECK: } // end sil function '_T014objc_protocols28testInitializableExistentialAA0D0_pAaC_pXp_Si1itF' class InitializableConformer: Initializable { @objc required init(int: Int) {} } // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols22InitializableConformerC{{[_0-9a-zA-Z]*}}fcTo final class InitializableConformerByExtension { init() {} } extension InitializableConformerByExtension: Initializable { @objc convenience init(int: Int) { self.init() } } // CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols33InitializableConformerByExtensionC{{[_0-9a-zA-Z]*}}fcTo // Make sure we're crashing from trying to use materializeForSet here. @objc protocol SelectionItem { var time: Double { get set } } func incrementTime(contents: SelectionItem) { contents.time += 1.0 }
apache-2.0
f9ddf17be1c6b71b80bbdf3ae719857b
42.862295
274
0.644939
3.403205
false
false
false
false
hrscy/TodayNews
News/News/Classes/Mine/Controller/UserDiggViewController.swift
1
2288
// // UserDiggViewController.swift // News // // Created by 杨蒙 on 2018/1/4. // Copyright © 2018年 hrscy. All rights reserved. // import UIKit import SVProgressHUD class UserDiggViewController: UITableViewController { var userId = 0 var digglist = [DongtaiUserDigg]() override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "赞过的人" SVProgressHUD.configuration() tableView.tableFooterView = UIView() tableView.ym_registerCell(cell: UserDiggCell.self) tableView.mj_footer = RefreshAutoGifFooter(refreshingBlock: { [weak self] in // 获取动态详情的用户点赞列表数据 NetworkTool.loadDongtaiDetailUserDiggList(id: self!.userId, offset: self!.digglist.count) { if self!.tableView.mj_footer.isRefreshing { self!.tableView.mj_footer.endRefreshing() } self!.tableView.mj_footer.pullingPercent = 0.0 if $0.count == 0 { self!.tableView.mj_footer.endRefreshingWithNoMoreData() SVProgressHUD.showInfo(withStatus: "没有更多数据啦!") return } self!.digglist = $0 self!.tableView.reloadData() } }) tableView.mj_footer.beginRefreshing() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return digglist.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.ym_dequeueReusableCell(indexPath: indexPath) as UserDiggCell cell.user = digglist[indexPath.row] return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let user = digglist[indexPath.row] let userDetailVC = UserDetailViewController2() userDetailVC.userId = user.user_id navigationController?.pushViewController(userDetailVC, animated: true) } }
mit
bcab18deab0a6b0b50d1033aec93c53b
33.828125
109
0.641543
4.888158
false
false
false
false
apple/swift-corelibs-foundation
Sources/Foundation/LengthFormatter.swift
2
10241
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // extension LengthFormatter { public enum Unit: Int { case millimeter = 8 case centimeter = 9 case meter = 11 case kilometer = 14 case inch = 1281 case foot = 1282 case yard = 1283 case mile = 1284 } } open class LengthFormatter : Formatter { public override init() { numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal unitStyle = .medium isForPersonHeightUse = false super.init() } public required init?(coder: NSCoder) { numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal unitStyle = .medium isForPersonHeightUse = false super.init(coder:coder) } /*@NSCopying*/ open var numberFormatter: NumberFormatter! // default is NumberFormatter with NumberFormatter.Style.decimal open var unitStyle: UnitStyle // default is NSFormattingUnitStyleMedium open var isForPersonHeightUse: Bool // default is NO; if it is set to YES, the number argument for -stringFromMeters: and -unitStringFromMeters: is considered as a person's height // Format a combination of a number and an unit to a localized string. open func string(fromValue value: Double, unit: LengthFormatter.Unit) -> String { guard let formattedValue = numberFormatter.string(from:NSNumber(value: value)) else { fatalError("Cannot format \(value) as string") } let separator = unitStyle == .short ? "" : " " return "\(formattedValue)\(separator)\(unitString(fromValue: value, unit: unit))" } // Format a number in meters to a localized string with the locale-appropriate unit and an appropriate scale (e.g. 4.3m = 14.1ft in the US locale). open func string(fromMeters numberInMeters: Double) -> String { //Convert to the locale-appropriate unit let unitFromMeters = unit(fromMeters: numberInMeters) //Map the unit to UnitLength type for conversion later let unitLengthFromMeters = LengthFormatter.unitLength[unitFromMeters]! //Create a measurement object based on the value in meters let meterMeasurement = Measurement<UnitLength>(value:numberInMeters, unit: .meters) //Convert the object to the locale-appropriate unit determined above let unitMeasurement = meterMeasurement.converted(to: unitLengthFromMeters) //Extract the number from the measurement let numberInUnit = unitMeasurement.value if isForPersonHeightUse && !numberFormatter.locale.usesMetricSystem { let feet = numberInUnit.rounded(.towardZero) let feetString = string(fromValue: feet, unit: .foot) let inches = abs(numberInUnit.truncatingRemainder(dividingBy: 1.0)) * 12 let inchesString = string(fromValue: inches, unit: .inch) return ("\(feetString), \(inchesString)") } return string(fromValue: numberInUnit, unit: unitFromMeters) } // Return a localized string of the given unit, and if the unit is singular or plural is based on the given number. open func unitString(fromValue value: Double, unit: Unit) -> String { if unitStyle == .short { return LengthFormatter.shortSymbol[unit]! } else if unitStyle == .medium { return LengthFormatter.mediumSymbol[unit]! } else if value == 1.0 { return LengthFormatter.largeSingularSymbol[unit]! } else { return LengthFormatter.largePluralSymbol[unit]! } } // Return the locale-appropriate unit, the same unit used by -stringFromMeters:. open func unitString(fromMeters numberInMeters: Double, usedUnit unitp: UnsafeMutablePointer<Unit>?) -> String { //Convert to the locale-appropriate unit let unitFromMeters = unit(fromMeters: numberInMeters) unitp?.pointee = unitFromMeters //Map the unit to UnitLength type for conversion later let unitLengthFromMeters = LengthFormatter.unitLength[unitFromMeters]! //Create a measurement object based on the value in meters let meterMeasurement = Measurement<UnitLength>(value:numberInMeters, unit: .meters) //Convert the object to the locale-appropriate unit determined above let unitMeasurement = meterMeasurement.converted(to: unitLengthFromMeters) //Extract the number from the measurement let numberInUnit = unitMeasurement.value //Return the appropriate representation of the unit based on the selected unit style return unitString(fromValue: numberInUnit, unit: unitFromMeters) } /// This method selects the appropriate unit based on the formatter’s locale, /// the magnitude of the value, and isForPersonHeightUse property. /// /// - Parameter numberInMeters: the magnitude in terms of meters /// - Returns: Returns the appropriate unit private func unit(fromMeters numberInMeters: Double) -> Unit { if numberFormatter.locale.usesMetricSystem { //Person height is always returned in cm for metric system if isForPersonHeightUse { return .centimeter } if numberInMeters > 1000 || numberInMeters < 0.0 { return .kilometer } else if numberInMeters > 1.0 { return .meter } else if numberInMeters > 0.01 { return .centimeter } else { return .millimeter } } else { //Person height is always returned in ft for U.S. system if isForPersonHeightUse { return .foot } let metricMeasurement = Measurement<UnitLength>(value:numberInMeters, unit: .meters) let usMeasurement = metricMeasurement.converted(to: .feet) let numberInFeet = usMeasurement.value if numberInFeet < 0.0 || numberInFeet > 5280 { return .mile } else if numberInFeet > 3 || numberInFeet == 0.0 { return .yard } else if numberInFeet >= 1.0 { return .foot } else { return .inch } } } /// Maps LengthFormatter.Unit enum to UnitLength class. Used for measurement conversion. private static let unitLength: [Unit:UnitLength] = [.millimeter:.millimeters, .centimeter:.centimeters, .meter:.meters, .kilometer:.kilometers, .inch:.inches, .foot:.feet, .yard:.yards, .mile:.miles] /// Maps a unit to its short symbol. Reuses strings from UnitLength wherever possible. private static let shortSymbol: [Unit: String] = [.millimeter:UnitLength.millimeters.symbol, .centimeter:UnitLength.centimeters.symbol, .meter:UnitLength.meters.symbol, .kilometer:UnitLength.kilometers.symbol, .inch:"″", .foot:"′", .yard:UnitLength.yards.symbol, .mile:UnitLength.miles.symbol] /// Maps a unit to its medium symbol. Reuses strings from UnitLength. private static let mediumSymbol: [Unit: String] = [.millimeter:UnitLength.millimeters.symbol, .centimeter:UnitLength.centimeters.symbol, .meter:UnitLength.meters.symbol, .kilometer:UnitLength.kilometers.symbol, .inch:UnitLength.inches.symbol, .foot:UnitLength.feet.symbol, .yard:UnitLength.yards.symbol, .mile:UnitLength.miles.symbol] /// Maps a unit to its large, singular symbol. private static let largeSingularSymbol: [Unit: String] = [.millimeter:"millimeter", .centimeter:"centimeter", .meter:"meter", .kilometer:"kilometer", .inch:"inch", .foot:"foot", .yard:"yard", .mile:"mile"] /// Maps a unit to its large, plural symbol. private static let largePluralSymbol: [Unit: String] = [.millimeter:"millimeters", .centimeter:"centimeters", .meter:"meters", .kilometer:"kilometers", .inch:"inches", .foot:"feet", .yard:"yards", .mile:"miles"] }
apache-2.0
fb21a98e177a0b37352e828730a8b48d
49.171569
183
0.540401
6.013514
false
false
false
false
andrea-prearo/swift-algorithm-data-structures-dojo
SwiftAlgorithmsAndDataStructuresDojoTests/Deque/DequeTests.swift
1
3604
// // DequeTests.swift // SwiftAlgorithmsAndDataStructuresDojoTests // // Created by Andrea Prearo on 3/17/17. // Copyright © 2017 Andrea Prearo. All rights reserved. // import XCTest @testable import SwiftAlgorithmsAndDataStructuresDojo class DequeTests: XCTestCase { static let integers = [5, -1, 8, 3, -24, 32, 0, 8] lazy var deque: Deque<Int> = { return Deque<Int>(array: DequeTests.integers) }() func testIsEmpty() { XCTAssertTrue(Deque<Int>().isEmpty) XCTAssertTrue(Deque<String>().isEmpty) } func testFront() { XCTAssertEqual(deque.front, 5) } func testBack() { XCTAssertEqual(deque.back, 8) } func testInitFromArray() { XCTAssertEqual(deque.count, DequeTests.integers.count) XCTAssertEqual(deque.array, DequeTests.integers) } func testCount() { XCTAssertEqual(deque.count, DequeTests.integers.count) XCTAssertEqual(Deque<Int>().count, 0) XCTAssertEqual(Deque(arrayLiteral: 1, 2, 3).count, 3) } func testPush() { let newValue = 1000 do { try deque.push(newValue) XCTAssertEqual(deque.front, 5) XCTAssertEqual(deque.back, newValue) } catch let error { XCTFail(error.localizedDescription) } } func testPushFront() { let newValue = 1000 do { try deque.pushFront(newValue) XCTAssertEqual(deque.front, newValue) XCTAssertEqual(deque.back, 8) } catch let error { XCTFail(error.localizedDescription) } } func testPop() { _ = (0..<deque.count).map { XCTAssertEqual(deque.pop(), SimpleQueueTests.integers[$0]) } XCTAssertNil(deque.pop()) } func testPopBack() { let maxIndex = StackTests.integers.count - 1 _ = (0..<deque.count).map { XCTAssertEqual(deque.popBack(), SimpleQueueTests.integers[maxIndex - $0]) } XCTAssertNil(deque.popBack()) } func testClear() { deque.clear() XCTAssertEqual(deque.count, 0) } func testDescription() { XCTAssertEqual(deque.description, String(describing: DequeTests.integers)) } func testSequence() { var index = 0 for item in deque { XCTAssertEqual(item, DequeTests.integers[index]) index += 1 } } func testExpressibleByArrayLiteral() { let deque = Deque(arrayLiteral: 0, 1, 2, 3) XCTAssertEqual(deque.count, 4) XCTAssertEqual(deque.array, [0, 1, 2, 3]) } func testAsArray() { XCTAssertEqual(deque.array, DequeTests.integers) } func testPushOutOfSpaceError() { let maxSize = 10 let deque = Deque<Int>(maxSize: maxSize) _ = (0..<maxSize).map { try? deque.push($0) } do { try deque.push(maxSize) } catch let error { XCTAssertEqual(error.localizedDescription, DequeueError.outOfSpace.localizedDescription) return } XCTFail("push didn't throw a StackError.outOfSpace exception") } func testPushFrontOutOfSpaceError() { let maxSize = 10 let deque = Deque<Int>(maxSize: maxSize) _ = (0..<maxSize).map { try? deque.pushFront($0) } do { try deque.pushFront(maxSize) } catch let error { XCTAssertEqual(error.localizedDescription, DequeueError.outOfSpace.localizedDescription) return } XCTFail("push didn't throw a StackError.outOfSpace exception") } }
mit
27c8b0b842da8aeeda0c35b502960694
27.370079
111
0.601166
4.459158
false
true
false
false
airspeedswift/swift
test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_struct.swift
3
11975
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment --check-prefix=CHECK --check-prefix=CHECK-%target-vendor // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$s4main5Value[[UNIQUE_ID_1:[A-Za-z0-9_]+]]CyAA4LeftACLLVySiGGMf" = linkonce_odr hidden // CHECK-apple-SAME: global // CHECK-unknown-SAME: constant // CHECK-SAME: <{ // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* // CHECK-SAME: )*, // CHECK-SAME: i8**, // : [[INT]], // CHECK-apple-SAME: %objc_class*, // CHECK-unknown-SAME: %swift.type*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: %swift.opaque*, // CHECK-apple-SAME: [[INT]], // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: i16, // CHECK-SAME: i16, // CHECK-SAME: i32, // CHECK-SAME: i32, // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: i8*, // CHECK-SAME: %swift.type*, // CHECK-SAME: [[INT]], // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* ( // CHECK-SAME: %swift.opaque*, // CHECK-SAME: %swift.type* // CHECK-SAME: )* // CHECK-SAME: }> <{ // CHECK-SAME: void ( // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* // : $s4main5Value[[UNIQUE_ID_1]]CfD // CHECK-SAME: $sBoWV // CHECK-apple-SAME: $s4main5Value[[UNIQUE_ID_1]]CyAA4LeftACLLVySiGGMM // CHECK-unknown-SAME: [[INT]] 0, // CHECK-apple-SAME: OBJC_CLASS_$__TtCs12_SwiftObject // CHECK-unknown-SAME: %swift.type* null, // CHECK-apple-SAME: %swift.opaque* @_objc_empty_cache, // CHECK-apple-SAME: %swift.opaque* null, // CHECK-apple-SAME: [[INT]] add ( // CHECK-apple-SAME: [[INT]] ptrtoint ( // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // : i32, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: { // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: [ // CHECK-apple-SAME: 1 x { // CHECK-apple-SAME: [[INT]]*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i32, // CHECK-apple-SAME: i32 // CHECK-apple-SAME: } // CHECK-apple-SAME: ] // CHECK-apple-SAME: }*, // CHECK-apple-SAME: i8*, // CHECK-apple-SAME: i8* // CHECK-apple-SAME: }* @_DATA__TtC4mainP[[UNIQUE_ID_2:[a-zA-Z0-9_]+]]5Value to [[INT]] // CHECK-apple-SAME: ), // CHECK-apple-SAME: [[INT]] 2 // CHECK-apple-SAME: ), // CHECK-SAME: i32 26, // CHECK-SAME: i32 0, // CHECK-SAME: i32 {{(24|12)}}, // CHECK-SAME: i16 {{(7|3)}}, // CHECK-SAME: i16 0, // CHECK-apple-SAME: i32 {{(120|72)}}, // CHECK-unknown-SAME: i32 96, // CHECK-SAME: i32 {{(16|8)}}, // : %swift.type_descriptor* bitcast ( // : <{ // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i32, // : i16, // : i16, // : i16, // : i16, // : i8, // : i8, // : i8, // : i8, // : i32, // : i32, // : %swift.method_descriptor // : }>* @"$s4main5Value[[UNIQUE_ID_1]]CMn" to %swift.type_descriptor* // : ), // CHECK-SAME: i8* null, // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32, // : [ // : 4 x i8 // : ], // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main4Left[[UNIQUE_ID_1]]VySiGMf" to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ), // CHECK-SAME: [[INT]] {{(16|8)}}, // CHECK-SAME: %T4main5Value[[UNIQUE_ID_1]]C* ( // CHECK-SAME: %swift.opaque*, // CHECK-SAME: %swift.type* // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]C5firstADyxGx_tcfC // CHECK-SAME: }>, // CHECK-SAME: align [[ALIGNMENT]] // CHECK: @"$s4main4Left[[UNIQUE_ID_1]]VySiGMf" = fileprivate class Value<First> { let first_Value: First init(first: First) { self.first_Value = first } } fileprivate struct Left<Value> { let left: Value } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: [[METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_4:[0-9A-Z_]+]]CyAA4LeftACLLVySiGGMb"([[INT]] 0) // CHECK: [[METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0 // CHECK: call swiftcc void @"$s4main7consumeyyxlF"( // CHECK-SAME: %swift.opaque* noalias nocapture {{%[0-9]+}}, // CHECK-SAME: %swift.type* [[METADATA]]) // CHECK: } func doit() { consume( Value(first: Left(left: 13)) ) } doit() // CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], %swift.type* %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_TYPE:%[0-9]+]] = bitcast %swift.type* %1 to i8* // CHECK: br label %[[TYPE_COMPARISON_LABEL:[0-9]+]] // CHECK: [[TYPE_COMPARISON_LABEL]]: // CHECK: [[EQUAL_TYPE:%[0-9]+]] = icmp eq i8* bitcast ( // CHECK-SAME: %swift.type* getelementptr inbounds ( // CHECK-SAME: %swift.full_type, // CHECK-SAME: %swift.full_type* bitcast ( // CHECK-SAME: <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i32, // : [ // : 4 x i8 // : ], // CHECK-SAME: i64 // CHECK-SAME: }>* @"$s4main4Left[[UNIQUE_ID_1]]VySiGMf" to %swift.full_type* // CHECK-SAME: ), // CHECK-SAME: i32 0, // CHECK-SAME: i32 1 // CHECK-SAME: ) to i8* // CHECK-SAME: ), // CHECK-SAME: [[ERASED_TYPE]] // CHECK: [[EQUAL_TYPES:%[0-9]+]] = and i1 true, [[EQUAL_TYPE]] // CHECK: br i1 [[EQUAL_TYPES]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]] // CHECK: [[EXIT_PRESPECIALIZED]]: // CHECK-NEXT: [[METADATA_RESPONSE:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_3:[0-9A-Z_]+]]CyAA4LeftACLLVySiGGMb"([[INT]] [[METADATA_REQUEST]]) // CHECK: [[METADATA:%[0-9]+]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0 // CHECK: [[PARTIAL_RESULT_METADATA:%[\" a-zA-Z0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[METADATA]], 0 // CHECK: [[RESULT_METADATA:%[\" a-zA-Z0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_RESULT_METADATA]], [[INT]] 0, 1 // CHECK: ret %swift.metadata_response [[RESULT_METADATA]] // CHECK: [[EXIT_NORMAL]]: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( // CHECK: [[INT]] [[METADATA_REQUEST]], // CHECK: i8* [[ERASED_TYPE]], // CHECK: i8* undef, // CHECK: i8* undef, // CHECK: %swift.type_descriptor* bitcast ( // : <{ i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i32, i16, i16, i16, i16, i8, i8, i8, i8, i32, i32, %swift.method_descriptor }>* // CHECK: $s4main5Value[[UNIQUE_ID_1]]CMn // CHECK: to %swift.type_descriptor* // CHECK: ) // CHECK: ) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: } // CHECK: ; Function Attrs: noinline nounwind readnone // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CyAA4LeftACLLVySiGGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} { // CHECK: entry: // CHECK-unknown: ret // CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call %objc_class* @objc_opt_self( // : %objc_class* bitcast ( // : %swift.type* getelementptr inbounds ( // : %swift.full_heapmetadata, // : %swift.full_heapmetadata* bitcast ( // : <{ // : void ( // : %T4main5Value[ // : [ // : UNIQUE_ID_1 // : ] // : ]C* // : )*, // : i8**, // : [[INT]], // : %objc_class*, // : %swift.opaque*, // : %swift.opaque*, // : [[INT]], // : i32, // : i32, // : i32, // : i16, // : i16, // : i32, // : i32, // : %swift.type_descriptor*, // : i8*, // : %swift.type*, // : [[INT]], // : %T4main5Value[ // : [ // : UNIQUE_ID_1 // : ] // : ]C* ( // : %swift.opaque*, // : %swift.type* // : )* // : }>* // CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1]]CyAA4LeftACLLVySiGGMf" // : to %swift.full_heapmetadata* // : ), // : i32 0, // : i32 2 // : ) to %objc_class* // : ) // : ) // CHECK-apple: [[INITIALIZED_METADATA:%[0-9]+]] = bitcast %objc_class* [[INITIALIZED_CLASS]] to %swift.type* // CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, %swift.type* [[INITIALIZED_METADATA]], 0 // CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 // CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] // CHECK: }
apache-2.0
8015d6adbe207c7707299e517b21121c
42.231047
214
0.44
3.287126
false
false
false
false
nodekit-io/nodekit-darwin
src/nodekit/NKScripting/util/NKArchive/NKAR_CentralDirectory.swift
1
5477
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. All Rights Reserved. * Portions Copyright (c) 2013 GitHub, Inc. under MIT License * Portions Copyright (c) 2015 lazyapps. 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 Darwin /* central file header signature 4 bytes (0x02014b50) version made by 2 bytes version needed to extract 2 bytes general purpose bit flag 2 bytes compression method 2 bytes last mod file time 2 bytes last mod file date 2 bytes crc-32 4 bytes compressed size 4 bytes uncompressed size 4 bytes file name length 2 bytes extra field length 2 bytes file comment length 2 bytes disk number start 2 bytes internal file attributes 2 bytes external file attributes 4 bytes relative offset of local header 4 bytes file name (variable size) extra field (variable size) file comment (variable size) */ enum NKAR_CompressionMethod { case None case Deflate init?(_ i: UInt16) { if i == 0 { self = .None } else if i == 8 { self = .Deflate } else { return nil } } } struct NKAR_CentralDirectory { let bytes: UnsafePointer<UInt8> let compressionMethod: NKAR_CompressionMethod let lastmodTime: UInt16 let lastmodDate: UInt16 let compressedSize: UInt32 let uncompressedSize: UInt32 let fileName: String let localFileHeaderOffset: UInt32 } extension NKAR_CentralDirectory { /* ZIP FILE FORMAT: CENTRAL DIRECTORY RECORD, INCLUDED WITHIN END RECORD local file header signature 4 bytes (0x04034b50) version needed to extract 2 bytes general purpose bit flag 2 bytes compression method 2 bytes last mod file time 2 bytes last mod file date 2 bytes crc-32 4 bytes compressed size 4 bytes uncompressed size 4 bytes file name length 2 bytes extra field length 2 bytes */ var dataOffset: Int { var reader = NKAR_BytesReader(bytes: bytes, index: Int(localFileHeaderOffset)) reader.skip(4 + 2 * 5 + 4 * 3) let fnLen = reader.le16() let efLen = reader.le16() reader.skip(Int(fnLen + efLen)) return reader.index } var lastmodUnixTimestamp: Int { var time = tm() time.tm_year = Int32((lastmodDate >> 9 & 0x7f) + 1980 - 1900) time.tm_mon = Int32((lastmodDate >> 5 & 0x0f) - 1 - 1) time.tm_mday = Int32(lastmodDate & 0x1f) time.tm_hour = Int32(lastmodTime >> 11 & 0x1f) time.tm_min = Int32(lastmodTime >> 5 & 0x3f) time.tm_sec = Int32((lastmodTime & 0x1f) << 1) let timestamp = mktime(&time) return timestamp } } extension NKAR_CentralDirectory { static let signature: UInt32 = 0x02014b50 static func findCentralDirectoriesInBytes(bytes: UnsafePointer<UInt8>, length: Int, withEndRecord er: NKAR_EndRecord) -> [String: NKAR_CentralDirectory]? { var reader = NKAR_BytesReader(bytes: bytes, index: Int(er.centralDirectoryOffset)) var dirs = [String: NKAR_CentralDirectory]() for _ in 0..<er.numEntries { let sign = reader.le32() if sign != signature { return dirs } reader.skip(2 + 2 + 2) let cMethodNum = reader.le16() let lmTime = reader.le16() let lmDate = reader.le16() reader.skip(4) let cSize = reader.le32() let ucSize = reader.le32() let fnLen = reader.le16() let efLen = reader.le16() let fcLen = reader.le16() reader.skip(2 + 2 + 4) let offset = reader.le32() if let fn = reader.string(Int(fnLen)), let cMethod = NKAR_CompressionMethod(cMethodNum) { dirs[fn] = NKAR_CentralDirectory(bytes: bytes, compressionMethod: cMethod, lastmodTime: lmTime, lastmodDate: lmDate, compressedSize: cSize, uncompressedSize: ucSize, fileName: fn, localFileHeaderOffset: offset) } reader.skip(Int(efLen + fcLen)) } return dirs.count > 0 ? dirs : nil } }
apache-2.0
64311d3864cbb757e10cca00acfdf411
27.38342
226
0.549754
4.618044
false
false
false
false
MartinOSix/DemoKit
dSwift/SwiftDemoKit/SwiftDemoKit/BaseAnimationViewController.swift
1
3371
// // BaseAnimationViewController.swift // SwiftDemoKit // // Created by runo on 17/5/26. // Copyright © 2017年 com.runo. All rights reserved. // import UIKit class BaseAnimationViewController: UIViewController,UITableViewDataSource,UITableViewDelegate { let tableView = UITableView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight/2), style: .plain) let dataSource = ["呼吸灯/透明度","摇摆","打开钉钉"] let showView = UIView.init(frame: CGRect.zero) override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(self.tableView) self.tableView.delegate = self self.tableView.dataSource = self self.showView.frame = CGRect.init(x: 100, y: kScreenHeight/2+100, width: 50, height: 50) self.showView.backgroundColor = UIColor.red self.view.addSubview(self.showView) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell") ?? UITableViewCell.init(style: .default, reuseIdentifier: "cell") cell.textLabel?.text = dataSource[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: baseAnimationOpacity() case 1: baseAnimationRotationZ() default: if UIApplication.shared.canOpenURL(URL.init(string: "dingtalk-open://")!){ UIApplication.shared.openURL(URL.init(string: "dingtalk-open://")!) } break } } func baseAnimationOpacity() { let baseAnimation = CABasicAnimation.init(keyPath: "opacity") baseAnimation.fromValue = NSNumber.init(value: 1.0) baseAnimation.toValue = NSNumber.init(value: 0.0) baseAnimation.autoreverses = true//动画可以逆向回去 baseAnimation.duration = 1.0 baseAnimation.repeatCount = MAXFLOAT baseAnimation.isRemovedOnCompletion = false baseAnimation.fillMode = kCAFillModeForwards baseAnimation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseIn) self.showView.layer.add(baseAnimation, forKey: "alpha") } func baseAnimationRotationZ() { self.showView.layer.position = CGPoint.init(x: self.showView.frame.midX, y: self.showView.frame.minY) self.showView.layer.anchorPoint = CGPoint.init(x: 0.5, y: 0) let baseAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z") baseAnimation.fromValue = NSNumber.init(value: 0) baseAnimation.toValue = NSNumber.init(value: 1) baseAnimation.duration = 1.0 baseAnimation.repeatCount = MAXFLOAT baseAnimation.isRemovedOnCompletion = false baseAnimation.autoreverses = true baseAnimation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut) baseAnimation.fillMode = kCAFillModeForwards self.showView.layer.add(baseAnimation, forKey: "Rotating") } }
apache-2.0
c6b69db8775df47e8d18f7abb7f61202
32.616162
138
0.667969
4.781609
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Vender/RoundedSwitch/Switch.swift
1
8570
// // Switch.swift // // Created by Thanh Pham on 8/24/16. // import UIKit /// A switch control @IBDesignable open class Switch: UIControl { let backgroundLayer = RoundLayer() let switchLayer = RoundLayer() let selectedColor: UIColor = text_color_bl51 let deselectedColor: UIColor = text_color_g153 var previousPoint: CGPoint? var switchLayerLeftPosition: CGPoint? var switchLayerRightPosition: CGPoint? static let labelFactory: () -> UILabel = { let label = UILabel() label.textAlignment = .center label.font = UIFont.systemFont(ofSize: 12, weight: UIFontWeightRegular) return label } /// The label on the left. Don't set the `textColor` and `text` properties on this label. Set them on the `leftText`, `tintColor` and `disabledColor` properties of the switch instead. open let leftLabel = labelFactory() /// The label on the right. Don't set the `textColor` and `text` properties on this label. Set them on the `rightText`, `tintColor` and `disabledColor` properties of the switch instead. open let rightLabel = labelFactory() /// Text for the label on the left. Setting this property instead of the `text` property of the `leftLabel` to trigger Auto Layout automatically. @IBInspectable open var leftText: String? { get { return leftLabel.text } set { leftLabel.text = newValue invalidateIntrinsicContentSize() } } /// Text for the label on the right. Setting this property instead of the `text` property of the `rightLabel` to trigger Auto Layout automatically. @IBInspectable open var rightText: String? { get { return rightLabel.text } set { rightLabel.text = newValue invalidateIntrinsicContentSize() } } /// True when the right value is selected, false when the left value is selected. When this property is changed, the UIControlEvents.ValueChanged is fired. @IBInspectable open var rightSelected: Bool = false { didSet { reloadSwitchLayerPosition() reloadLabelsTextColor() sendActions(for: .valueChanged) } } /// The color used for the unselected text and the background border. @IBInspectable open var disabledColor: UIColor = UIColor.lightGray { didSet { backgroundLayer.borderColor = disabledColor.cgColor switchLayer.borderColor = disabledColor.cgColor reloadLabelsTextColor() } } /// The color used for the selected text and the switch border. override open var tintColor: UIColor! { didSet { reloadLabelsTextColor() } } var touchBegan = false var touchBeganInSwitchLayer = false var touchMoved = false /// Init with coder. required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } func setup() { backgroundLayer.backgroundColor = UIColor.init(colorLiteralRed: 245/255, green: 245/255, blue: 250/255, alpha: 1).cgColor backgroundLayer.borderColor = disabledColor.cgColor backgroundLayer.borderWidth = 1 layer.addSublayer(backgroundLayer) switchLayer.backgroundColor = UIColor.white.cgColor switchLayer.borderColor = disabledColor.cgColor switchLayer.borderWidth = 1 layer.addSublayer(switchLayer) addSubview(leftLabel) addSubview(rightLabel) reloadLabelsTextColor() } /// Layouts subviews. Should not be called directly. override open func layoutSubviews() { super.layoutSubviews() leftLabel.frame = CGRect(x: 0, y: 0, width: bounds.size.width / 2, height: bounds.size.height) rightLabel.frame = CGRect(x: bounds.size.width / 2, y: 0, width: bounds.size.width / 2, height: bounds.size.height) } /// Layouts sublayers of a layer. Should not be called directly. override open func layoutSublayers(of layer: CALayer) { super.layoutSublayers(of: layer) guard layer == self.layer else { return } backgroundLayer.frame = layer.bounds switchLayer.bounds = CGRect(x: 0, y: 0, width: layer.bounds.size.width / 2, height: layer.bounds.size.height) switchLayerLeftPosition = layer.convert(layer.position, from: layer.superlayer).applying(CGAffineTransform(translationX: -switchLayer.bounds.size.width / 2, y: 0)) switchLayerRightPosition = switchLayerLeftPosition!.applying(CGAffineTransform(translationX: switchLayer.bounds.size.width, y: 0)) touchBegan = false touchBeganInSwitchLayer = false touchMoved = false previousPoint = nil reloadSwitchLayerPosition() } /// Touches began event handler. Should not be called directly. override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) touchBegan = true previousPoint = touches.first!.location(in: self) touchBeganInSwitchLayer = switchLayer.contains(switchLayer.convert(previousPoint!, from: layer)) } /// Touches moved event handler. Should not be called directly. override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) touchMoved = true guard touchBeganInSwitchLayer else { return } let point = touches.first!.location(in: self) var position = switchLayer.position.applying(CGAffineTransform(translationX: point.x - previousPoint!.x, y: 0)) position.x = max(switchLayer.bounds.size.width / 2, min(layer.bounds.size.width - switchLayer.bounds.size.width / 2, position.x)) switchLayer.position = position previousPoint = point } /// Touches ended event handler. Should not be called directly. override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) guard touchBegan else { return } previousPoint = nil if touchMoved && touchBeganInSwitchLayer { rightSelected = abs(switchLayerLeftPosition!.x - switchLayer.position.x) > abs(switchLayerRightPosition!.x - switchLayer.position.x) } else if !touchMoved && !touchBeganInSwitchLayer { rightSelected = !rightSelected } touchBegan = false touchBeganInSwitchLayer = false touchMoved = false } /// Touches cancelled event handler. Should not be called directly. override open func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) previousPoint = nil reloadSwitchLayerPosition() touchBegan = false touchBeganInSwitchLayer = false touchMoved = false } /// Returns the minimum size that fits a given size. override open func sizeThatFits(_ size: CGSize) -> CGSize { let labelSize = CGSize(width: (size.width - 3 * size.height / 2) / 2, height: size.height) return desiredSizeForLeftSize(leftLabel.sizeThatFits(labelSize), rightSize: rightLabel.sizeThatFits(labelSize)) } /// The minimum size used for Auto Layout. override open var intrinsicContentSize : CGSize { return desiredSizeForLeftSize(leftLabel.intrinsicContentSize, rightSize: rightLabel.intrinsicContentSize) } func desiredSizeForLeftSize(_ leftSize: CGSize, rightSize: CGSize) -> CGSize { let height = max(leftSize.height, rightSize.height) return CGSize(width: max(leftSize.width, rightSize.width) * 2 + 3 * height / 2, height: height) } func reloadLabelsTextColor() { leftLabel.textColor = rightSelected ? deselectedColor : selectedColor rightLabel.textColor = rightSelected ? selectedColor : deselectedColor } func reloadSwitchLayerPosition() { guard let switchLayerLeftPosition = switchLayerLeftPosition, let switchLayerRightPosition = switchLayerRightPosition else { return } switchLayer.position = rightSelected ? switchLayerRightPosition : switchLayerLeftPosition } } class RoundLayer: CALayer { override func layoutSublayers() { super.layoutSublayers() cornerRadius = bounds.size.height / 2 } }
mit
c621ab93a5d953ce9dbb236e85a502ee
37.778281
189
0.669545
5.065012
false
false
false
false
yl-github/YLDYZB
YLDouYuZB/YLDouYuZB/Classes/Home/Controller/YLFunnyViewController.swift
1
1107
// // YLFunnyViewController.swift // YLDouYuZB // // Created by yl on 2016/10/19. // Copyright © 2016年 yl. All rights reserved. // import UIKit private let kTopMargin : CGFloat = 8 class YLFunnyViewController: YLBaseAnchorViewController { //MARK:- 定义属性 var funnyViewModel : YLFunnyViewModel = YLFunnyViewModel(); } extension YLFunnyViewController { override func setupUI() { super.setupUI(); let layout = recommendCollectionView.collectionViewLayout as! UICollectionViewFlowLayout; layout.headerReferenceSize = CGSize.zero; recommendCollectionView.contentInset = UIEdgeInsets(top: kTopMargin, left: 0, bottom: 0, right: 0); } } extension YLFunnyViewController { override func loadData() { // 将viewmodel传递给父类 self.baseViewModel = self.funnyViewModel; funnyViewModel.loadFunnyData { self.recommendCollectionView.reloadData(); // 请求完成,停止加载图片的动画 self.loadDataFinished(); } } }
mit
861ae42baa07931e523b16f53eca44db
24.142857
107
0.651515
4.844037
false
false
false
false
DivineDominion/mac-appdev-code
CoreDataOnly/ManageBoxesAndItems.swift
1
805
import Cocoa open class ManageBoxesAndItems { public init() { } lazy var repository: BoxRepository = ServiceLocator.boxRepository() lazy var windowController: ItemManagementWindowController! = { let controller = ItemManagementWindowController() controller.loadWindow() return controller }() open lazy var itemViewController: ItemViewController = { return self.windowController.itemViewController }() open func showBoxManagementWindow() { prepareWindow() showWindow() } func prepareWindow() { windowController.repository = self.repository } func showWindow() { windowController.showWindow(self) windowController.window?.makeKeyAndOrderFront(self) } }
mit
de86c40b33865375b2112364175f4750
24.967742
71
0.658385
5.70922
false
false
false
false
plivesey/SwiftGen
swiftgen-cli/main.swift
1
1826
// // SwiftGen // Copyright (c) 2015 Olivier Halligon // MIT Licence // import Commander import GenumKit import PathKit // MARK: Common let templatesRelativePath = (Bundle.main.resourcePath ?? ".") + "/templates" func templateOption(prefix: String) -> Option<String> { return Option<String>( "template", "default", flag: "t", description: "The name of the template to use for code generation " + "(without the \"\(prefix)\" prefix nor extension)." ) } let templatePathOption = Option<String>( "templatePath", "", flag: "p", description: "The path of the template to use for code generation. Overrides -t." ) let outputOption = Option( "output", OutputDestination.Console, flag: "o", description: "The path to the file to generate (Omit to generate to stdout)" ) // MARK: - Main let main = Group { $0.group("templates", "manage custom templates") { $0.addCommand("list", "list bundled and custom templates", templatesListCommand) $0.addCommand("which", "print path of a given named template", templatesWhichCommand) $0.addCommand("cat", "print content of a given named template", templatesCatCommand) } $0.addCommand("colors", "generate code for UIColors", colorsCommand) $0.addCommand("images", "generate code for UIImages based on your Assets Catalog", imagesCommand) $0.addCommand("storyboards", "generate code for your Storyboard scenes and segues", storyboardsCommand) $0.addCommand("strings", "generate code for your Localizable.strings", stringsCommand) $0.addCommand("fonts", "generate code for your UIFonts", fontsCommand) $0.addCommand("json", "generate any code from a JSON spec", jsonCommand) } let version = Bundle(for: GenumKit.GenumTemplate.self) .infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.0" main.run("SwiftGen v\(version)")
mit
cb20dbd61b3d5463a98da7050c66f6bc
34.803922
105
0.717415
3.978214
false
false
false
false
tnantoka/Feeder
Pod/Classes/Feeder.swift
1
758
// // Feeder.swift // Pods // // Created by Tatsuya Tobioka on 11/19/15. // // import Foundation public class Feeder { public static let shared = Feeder() public typealias FinderCallback = (Page, NSError?) -> Void public typealias ParserCallback = ([Entry], NSError?) -> Void public var session = NSURLSession.sharedSession() public func find(urlString: String, callback: FinderCallback) { let _ = Finder(urlString: urlString, callback: callback) } public func parse(urlString: String, callback: ParserCallback) { let _ = Parser(urlString: urlString, callback: callback) } public func parse(feed: Feed, callback: ParserCallback) { parse(feed.href, callback: callback) } }
mit
823c294de946f2eaa8c1b9b03c06ad04
24.266667
68
0.658311
4.282486
false
false
false
false
scotlandyard/expocity
expocity/Model/Chat/Item/Base/MChatItem.swift
1
689
import UIKit class MChatItem { weak var cell:VChatConversationCell? let reusableIdentifier:String var cellWidth:CGFloat var cellHeight:CGFloat init(reusableIdentifier:String) { self.reusableIdentifier = reusableIdentifier cellWidth = 0 cellHeight = 0 } //MARK: public func heightForCurrentWidth() -> CGFloat { return 0 } func heightForCollection(width:CGFloat) -> CGFloat { if width != cellWidth { cellWidth = width cellHeight = heightForCurrentWidth() cell?.layoutConstraints() } return cellHeight } }
mit
4facf527cb9a8f7b6afd41a782ff2f07
18.685714
54
0.582003
5.556452
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Maps/Display device location with autopan modes/DisplayLocationSettingsViewController.swift
1
5178
// Copyright 2018 Esri. // // 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 ArcGIS class DisplayLocationSettingsViewController: UITableViewController { // MARK: - Outlets @IBOutlet weak var showSwitch: UISwitch? @IBOutlet weak var autoPanModeCell: UITableViewCell? // MARK: - Model /// The SDK object for displaying the device location. Attached to the map view. weak var locationDisplay: AGSLocationDisplay? { didSet { updateUIForLocationDisplay() } } /// Returns a suitable interface label `String` for the mode. private func label(for autoPanMode: AGSLocationDisplayAutoPanMode) -> String { switch autoPanMode { case .off: return "Off" case .recenter: return "Re-Center" case .navigation: return "Navigation" case .compassNavigation: return "Compass Navigation" @unknown default: return "Unknown" } } private func icon(for autoPanMode: AGSLocationDisplayAutoPanMode) -> UIImage? { switch autoPanMode { case .off: return #imageLiteral(resourceName: "LocationDisplayOffIcon") case .recenter: return #imageLiteral(resourceName: "LocationDisplayDefaultIcon") case .navigation: return #imageLiteral(resourceName: "LocationDisplayNavigationIcon") case .compassNavigation: return #imageLiteral(resourceName: "LocationDisplayHeadingIcon") @unknown default: return nil } } // MARK: - Views override func viewDidLoad() { super.viewDidLoad() // setup the UI for the initial model values updateUIForLocationDisplay() // The auto-pan mode may be updated by the SDK as well as the user, // so use the change handler to set the UI locationDisplay?.autoPanModeChangedHandler = { [weak self] (_) in // update the UI for the new mode self?.updateUIForAutoPanMode() } } private func updateUIForLocationDisplay() { showSwitch?.isOn = locationDisplay?.started == true updateUIForAutoPanMode() } private func updateUIForAutoPanMode() { if let autoPanMode = locationDisplay?.autoPanMode { autoPanModeCell?.detailTextLabel?.text = label(for: autoPanMode) } } // MARK: - Actions @IBAction func showLocationSwitchAction(_ sender: UISwitch) { guard let locationDisplay = locationDisplay, // don't restart showing the location if it's already started locationDisplay.started != sender.isOn else { return } if sender.isOn { // To be able to request user permissions to get the device location, // make sure to add the location request field in the info.plist file // attempt to start showing the device location locationDisplay.start { [weak self] (error: Error?) in if let error = error { // show the error if one occurred self?.presentAlert(error: error) } } } else { // stop showing the device location locationDisplay.stop() } } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let cell = tableView.cellForRow(at: indexPath) else { return } /// The modes in the order we want to display them in the interface. let orderedAutoPanModes = [AGSLocationDisplayAutoPanMode.off, .recenter, .navigation, .compassNavigation] if cell == autoPanModeCell, let autoPanMode = locationDisplay?.autoPanMode, let selectedIndex = orderedAutoPanModes.firstIndex(of: autoPanMode) { let options = orderedAutoPanModes.map { OptionsTableViewController.Option(label: label(for: $0), image: icon(for: $0)) } let controller = OptionsTableViewController(options: options, selectedIndex: selectedIndex) { (index) in // get the mode for the index let autoPanMode = orderedAutoPanModes[index] // set the displayed location mode to the selected one self.locationDisplay?.autoPanMode = autoPanMode } controller.title = cell.textLabel?.text show(controller, sender: self) } } }
apache-2.0
06f3e45ec8c3877196a801cc893f99c0
35.464789
132
0.619158
5.388137
false
false
false
false
quickthyme/PUTcat
PUTcat/Presentation/TransactionResponse/TransactionResponseViewController.swift
1
2687
import UIKit protocol TransactionResponseViewControllerInput : ViewDataItemSettable, ParentViewDataItemSettable, BasicAlertPresentable, ProgressDisplayable, ProjectIDSettable { func displayViewData(_ viewData: TransactionResponseViewData) func refreshView(_ sender: AnyObject?) } protocol TransactionResponseViewControllerDelegate { func getViewData(refID: String, parentRefID: String, viewController: TransactionResponseViewControllerInput) } class TransactionResponseViewController : UITableViewController { var viewData : TransactionResponseViewData = TransactionResponseViewData(section: []) var viewDataItem : ViewDataItem = TransactionResponseViewDataItem() var viewDataParent : ViewDataItem = TransactionResponseViewDataItem() var projectID: String? @IBOutlet weak var delegateObject : AnyObject? var delegate : TransactionResponseViewControllerDelegate? { return delegateObject as? TransactionResponseViewControllerDelegate } var hasAppeared : Bool = false var buttonItemsNorm : [UIBarButtonItem] { return [] } } // MARK: - Lifecycle extension TransactionResponseViewController { override func viewDidLoad() { super.viewDidLoad() self.setupNavigationBar() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.beginObservingKeyboardNotifications() self.handleFirstWillAppear(animated) } private func handleFirstWillAppear(_ animated: Bool) { guard self.hasAppeared == false else { return } self.hasAppeared = true self.refreshView(nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.endObservingKeyboardNotifications() } private func setupNavigationBar() { self.navigationItem.setRightBarButtonItems(buttonItemsNorm, animated: false) } } // MARK: - TransactionResponseViewControllerInput extension TransactionResponseViewController : TransactionResponseViewControllerInput { func set(viewDataItem: ViewDataItem) { self.viewDataItem = viewDataItem self.navigationItem.title = viewDataItem.title } func set(parentViewDataItem: ViewDataItem) { self.viewDataParent = parentViewDataItem } func displayViewData(_ viewData: TransactionResponseViewData) { self.viewData = viewData self.tableView?.reloadData() self.refreshControl?.endRefreshing() } @IBAction func refreshView(_ sender: AnyObject?) { self.delegate?.getViewData(refID: viewDataItem.refID, parentRefID: viewDataParent.refID, viewController: self) } }
apache-2.0
0029e27f09f63e0aa5b072b983355bef
31.768293
118
0.743208
5.741453
false
false
false
false
tardieu/swift
benchmark/single-source/NSStringConversion.swift
5
778
//===--- NSStringConversion.swift -----------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // <rdar://problem/19003201> import TestsUtils import Foundation public func run_NSStringConversion(_ N: Int) { let test:NSString = NSString(cString: "test", encoding: String.Encoding.ascii.rawValue)! for _ in 1...N * 10000 { _ = test as String } }
apache-2.0
bd58bf8ef98ed85e7bb7857b9a180aa5
34.363636
88
0.601542
4.576471
false
true
false
false
pattypatpat2632/EveryoneGetsToDJ
EveryoneGetsToDJ/EveryoneGetsToDJ/MultipeerResource.swift
1
947
// // MultipeerResource.swift // EveryoneGetsToDJ // // Created by Patrick O'Leary on 6/19/17. // Copyright © 2017 Patrick O'Leary. All rights reserved. // import Foundation struct MultipeerResource: Serializing { enum Method: String { case send, remove } var method: Method var jukebox: Jukebox func asDictionary() -> [String: Any]{ return [ "method": method.rawValue, "jukebox":jukebox.asDictionary() ] } } extension MultipeerResource { init(dictionary: [String: Any]) { let methodValue = dictionary["method"] as? String ?? "" self.method = Method(rawValue: methodValue) ?? .send let jukeboxValues = dictionary["jukebox"] as? [String: Any] ?? [:] let id = jukeboxValues["id"] as? String ?? "" let newJukebox = Jukebox(id: id, dictionary: jukeboxValues) self.jukebox = newJukebox } }
mit
d42ee5fb434a2a8ba68f6d92053b6e52
25.277778
74
0.597252
4.113043
false
false
false
false
LeoMobileDeveloper/PullToRefreshKit
Demo/Demo/QQVideoRefreshHeader.swift
1
2013
// // QQVideoRefreshHeader.swift // PullToRefreshKit // // Created by huangwenchen on 16/8/1. // Copyright © 2016年 Leo. All rights reserved. // import Foundation import UIKit import PullToRefreshKit class QQVideoRefreshHeader:UIView,RefreshableHeader{ let imageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) imageView.frame = CGRect(x: 0, y: 0, width: 27, height: 10) imageView.center = CGPoint(x: self.bounds.width/2.0, y: self.bounds.height/2.0) imageView.image = UIImage(named: "loading15") addSubview(imageView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - RefreshableHeader - func heightForHeader() -> CGFloat { return 50.0 } func stateDidChanged(_ oldState: RefreshHeaderState, newState: RefreshHeaderState) { if newState == .pulling{ UIView.animate(withDuration: 0.3, animations: { self.imageView.transform = CGAffineTransform.identity }) } if newState == .idle{ UIView.animate(withDuration: 0.3, animations: { self.imageView.transform = CGAffineTransform(translationX: 0, y: -50) }) } } //松手即将刷新的状态 func didBeginRefreshingState(){ imageView.image = nil let images = (0...29).map{return $0 < 10 ? "loading0\($0)" : "loading\($0)"} imageView.animationImages = images.map{return UIImage(named:$0)!} imageView.animationDuration = Double(images.count) * 0.04 imageView.startAnimating() } //刷新结束,将要隐藏header func didBeginHideAnimation(_ result:RefreshResult){} //刷新结束,完全隐藏header func didCompleteHideAnimation(_ result:RefreshResult){ imageView.animationImages = nil imageView.stopAnimating() imageView.image = UIImage(named: "loading15") } }
mit
0807abe44cfada7691f60371ab558574
32.724138
88
0.633947
4.298901
false
false
false
false
svedm/SweetyViperDemo
SweetyViperDemo/SweetyViperDemoTests/Module/Second/Assembly/SecondAssemblyTests.swift
1
2218
// // SecondSecondAssemblyTests.swift // SweetyViperDemo // // Created by Svetoslav Karasev on 14/02/2017. // Copyright © 2017 Svedm. All rights reserved. // import Quick import Nimble import Swinject import SwinjectStoryboard @testable import SweetyViperDemo class SecondModuleAssemblySpec: QuickSpec { override func spec() { let assembler = try! Assembler(assemblies: [SecondModuleAssembly()]) let swinjectStoryboard = SwinjectStoryboard.create(name: "Main", bundle: Bundle(for: SecondViewController.self), container: assembler.resolver) let viewInput = swinjectStoryboard.instantiateViewController(withIdentifier: "SecondViewController") describe("Checking module creation") { it("Must be SecondViewController") { expect(viewInput).to(beAKindOf(SecondViewController.self)) } let viewController = viewInput as! SecondViewController it("Must contain correct output") { expect(viewController.output).toNot(beNil()) expect(viewController.output).to(beAKindOf(SecondPresenter.self)) } let presenter = viewController.output as! SecondPresenter it("Must contain view, interactor & router") { expect(presenter.view).toNot(beNil()) expect(presenter.router).toNot(beNil()) expect(presenter.interactor).toNot(beNil()) } let interactor: SecondInteractor = presenter.interactor as! SecondInteractor it("Must contain output") { expect(interactor.output).toNot(beNil()) } let router: SecondRouter = presenter.router as! SecondRouter it("Must contain transition handler") { expect(router.transitionHandler).toNot(beNil()) } } } class SecondViewControllerMock: SecondViewController { var setupInitialStateDidCall = false override func setupInitialState(_ name: String?) { setupInitialStateDidCall = true } } }
mit
515897596da4f1d2ef254e77bcecd944
34.758065
108
0.611186
5.670077
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/Authentication/Interface/Views/PhoneNumberInputView.swift
1
14406
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit import WireDataModel import WireCommonComponents /// An object that receives notification about the phone number input view. protocol PhoneNumberInputViewDelegate: AnyObject { func phoneNumberInputView(_ inputView: PhoneNumberInputView, didPickPhoneNumber phoneNumber: PhoneNumber) func phoneNumberInputView(_ inputView: PhoneNumberInputView, didValidatePhoneNumber phoneNumber: PhoneNumber, withResult validationError: TextFieldValidator.ValidationError?) func phoneNumberInputViewDidRequestCountryPicker(_ inputView: PhoneNumberInputView) } /** * A view providing an input field for phone numbers and a button for choosing the country. */ class PhoneNumberInputView: UIView, UITextFieldDelegate, TextFieldValidationDelegate, TextContainer { /// The object receiving notifications about events from this view. weak var delegate: PhoneNumberInputViewDelegate? /// The currently selected country. private(set) var country = Country.defaultCountry /// The validation error for the current input. private(set) var validationError: TextFieldValidator.ValidationError? = .tooShort(kind: .phoneNumber) var hasPrefilledValue: Bool = false var allowEditingPrefilledValue: Bool = true { didSet { updatePhoneNumberInputFieldIsEnabled() } } var allowEditing: Bool { return !hasPrefilledValue || allowEditingPrefilledValue } /// Whether to show the confirm button. var showConfirmButton: Bool = true { didSet { textField.showConfirmButton = showConfirmButton } } /// The value entered by the user. var input: String { return textField.input } var text: String? { get { return textField.text } set { hasPrefilledValue = newValue != nil textField.text = newValue updatePhoneNumberInputFieldIsEnabled() } } // MARK: - Views private let countryPickerButton = IconButton() private let inputStack = UIStackView() private let countryCodeInputView = IconButton() private let textField = ValidatedTextField(kind: .phoneNumber, leftInset: 8) // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) configureSubviews() configureConstraints() configureValidation() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func configureSubviews() { // countryPickerButton countryPickerButton.accessibilityIdentifier = "CountryPickerButton" countryPickerButton.titleLabel?.font = UIFont.normalLightFont countryPickerButton.contentHorizontalAlignment = UIApplication.isLeftToRightLayout ? .left : .right countryPickerButton.addTarget(self, action: #selector(handleCountryButtonTap), for: .touchUpInside) countryPickerButton.setContentHuggingPriority(.defaultLow, for: .horizontal) addSubview(countryPickerButton) // countryCodeButton countryCodeInputView.setContentHuggingPriority(.required, for: .horizontal) countryCodeInputView.setBackgroundImageColor(.white, for: .normal) countryCodeInputView.setTitleColor(UIColor.Team.textColor, for: .normal) countryCodeInputView.titleLabel?.font = FontSpec(.normal, .regular, .inputText).font countryCodeInputView.titleEdgeInsets.top = -1 countryCodeInputView.isUserInteractionEnabled = false countryCodeInputView.accessibilityTraits = [.staticText] inputStack.addArrangedSubview(countryCodeInputView) // inputStack inputStack.axis = .horizontal inputStack.spacing = 0 inputStack.distribution = .fill inputStack.alignment = .fill addSubview(inputStack) // textField textField.textInsets.left = 0 textField.placeholder = "registration.enter_phone_number.placeholder".localized(uppercased: true) textField.accessibilityLabel = "registration.enter_phone_number.placeholder".localized textField.accessibilityIdentifier = "PhoneNumberField" textField.tintColor = UIColor.Team.activeButtonColor textField.confirmButton.addTarget(self, action: #selector(handleConfirmButtonTap), for: .touchUpInside) textField.delegate = self textField.textFieldValidationDelegate = self inputStack.addArrangedSubview(textField) selectCountry(.defaultCountry) } private func configureConstraints() { inputStack.translatesAutoresizingMaskIntoConstraints = false countryPickerButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ // countryPickerStack countryPickerButton.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16), countryPickerButton.topAnchor.constraint(equalTo: topAnchor), countryPickerButton.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -16), countryPickerButton.heightAnchor.constraint(equalToConstant: 28), // inputStack inputStack.leadingAnchor.constraint(equalTo: leadingAnchor), inputStack.topAnchor.constraint(equalTo: countryPickerButton.bottomAnchor, constant: 16), inputStack.trailingAnchor.constraint(equalTo: trailingAnchor), inputStack.bottomAnchor.constraint(equalTo: bottomAnchor), // dimentions textField.heightAnchor.constraint(equalToConstant: 56), countryCodeInputView.widthAnchor.constraint(equalToConstant: 60) ]) } private func configureValidation() { textField.enableConfirmButton = { [weak self] in self?.validationError == nil } textField.textFieldValidator.customValidator = { input in let phoneNumber = self.country.e164PrefixString + input let normalizedNumber = UnregisteredUser.normalizedPhoneNumber(phoneNumber) switch normalizedNumber { case .invalid(let errorCode): switch errorCode { case .tooLong: return .tooLong(kind: .phoneNumber) case .tooShort: return .tooShort(kind: .phoneNumber) default: return .invalidPhoneNumber } case .unknownError: return .invalidPhoneNumber case .valid: return .none } } } // MARK: - Customization var inputBackgroundColor: UIColor = .white { didSet { countryCodeInputView.setBackgroundImageColor(inputBackgroundColor, for: .normal) textField.backgroundColor = inputBackgroundColor } } var textColor: UIColor = UIColor.Team.textColor { didSet { countryCodeInputView.setTitleColor(textColor, for: .normal) textField.textColor = textColor updateCountryButtonLabel() } } // MARK: - View Lifecycle override var canBecomeFirstResponder: Bool { return textField.canBecomeFirstResponder } override var isFirstResponder: Bool { return textField.isFirstResponder } override func becomeFirstResponder() -> Bool { return textField.becomeFirstResponder() } override var canResignFirstResponder: Bool { return textField.canResignFirstResponder } @discardableResult override func resignFirstResponder() -> Bool { return textField.resignFirstResponder() } /** * Selects the specified country as the beginning of the phone number. * - parameter country: The country of the phone number, */ func selectCountry(_ country: Country) { self.country = country updateCountryButtonLabel() countryPickerButton.accessibilityValue = country.displayName countryPickerButton.accessibilityLabel = "registration.phone_country".localized countryCodeInputView.setTitle(country.e164PrefixString, for: .normal) countryCodeInputView.accessibilityLabel = "registration.phone_code".localized countryCodeInputView.accessibilityValue = country.e164PrefixString } private func updateCountryButtonLabel() { let title = country.displayName let color = textColor let selectedColor = textColor.withAlphaComponent(0.4) tintColor = color let icon = NSTextAttachment.downArrow(color: color) let selectedIcon = NSTextAttachment.downArrow(color: selectedColor) let normalLabel = title.addingTrailingAttachment(icon, verticalOffset: 1) && color countryPickerButton.setAttributedTitle(normalLabel, for: .normal) let selectedLabel = title.addingTrailingAttachment(selectedIcon, verticalOffset: 1) && selectedColor countryPickerButton.setAttributedTitle(selectedLabel, for: .highlighted) } /// Sets the phone number to display. func setPhoneNumber(_ phoneNumber: PhoneNumber) { hasPrefilledValue = true selectCountry(phoneNumber.country) textField.updateText(phoneNumber.numberWithoutCode) updatePhoneNumberInputFieldIsEnabled() } func updatePhoneNumberInputFieldIsEnabled() { countryPickerButton.isEnabled = allowEditing } // MARK: - Text Update /// Returns whether the text should be updated. func shouldChangeCharacters(in range: NSRange, replacementString: String) -> Bool { guard allowEditing, let replacementRange = Range(range, in: input) else { return false } let updatedString = input.replacingCharacters(in: replacementRange, with: replacementString) return shouldUpdatePhoneNumber(updatedString) } /// Updates the phone number with a new value. private func shouldUpdatePhoneNumber(_ updatedString: String?) -> Bool { guard let updatedString = updatedString else { return false } // If the textField is empty and a replacementString with a +, it is likely to insert from autoFill. if textField.text?.count == 0 && updatedString.contains("+") { return shouldInsert(phoneNumber: updatedString) } var number = PhoneNumber(countryCode: country.e164, numberWithoutCode: updatedString) switch number.validate() { case .containsInvalidCharacters, .tooLong: return false default: return true } } // MARK: - Events @objc private func handleCountryButtonTap() { delegate?.phoneNumberInputViewDidRequestCountryPicker(self) } @objc private func handleConfirmButtonTap() { submitValue() } override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { if action == #selector(UIResponderStandardEditActions.paste(_:)) { return UIPasteboard.general.hasStrings } else { return super.canPerformAction(action, withSender: sender) } } /// Do not paste if we need to set the text manually. override func paste(_ sender: Any?) { var shouldPaste = true if UIPasteboard.general.hasStrings { shouldPaste = shouldInsert(phoneNumber: UIPasteboard.general.string ?? "") } if shouldPaste { textField.paste(sender) } } /// Only insert text if we have a valid phone number. func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return shouldChangeCharacters(in: range, replacementString: string) } /** * Checks whether the inserted text contains a phone number. If it does, we overtake the paste / text change mechanism and * update the country and text field manually. * - parameter phoneNumber: The text that is being inserted. * - returns: Whether the text should be inserted by the text field or if we need to insert it manually. */ private func shouldInsert(phoneNumber: String) -> Bool { guard let (country, phoneNumberWithoutCountryCode) = phoneNumber.shouldInsertAsPhoneNumber(presetCountry: country) else { return true } selectCountry(country) textField.updateText(phoneNumberWithoutCountryCode) return false } // MARK: - Value Submission func validationUpdated(sender: UITextField, error: TextFieldValidator.ValidationError?) { self.validationError = error let phoneNumber = PhoneNumber(countryCode: country.e164, numberWithoutCode: input) delegate?.phoneNumberInputView(self, didValidatePhoneNumber: phoneNumber, withResult: validationError) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.textField.validateInput() if self.validationError == .none { submitValue() return true } else { return false } } func submitValue() { var phoneNumber = PhoneNumber(countryCode: country.e164, numberWithoutCode: textField.input) let validationResult = phoneNumber.validate() delegate?.phoneNumberInputView(self, didValidatePhoneNumber: phoneNumber, withResult: validationError) if validationError == nil && validationResult == .valid { delegate?.phoneNumberInputView(self, didValidatePhoneNumber: phoneNumber, withResult: nil) delegate?.phoneNumberInputView(self, didPickPhoneNumber: phoneNumber) } } }
gpl-3.0
c7110cca0ae78f4176f85fea0fc7333a
36.033419
178
0.689504
5.705347
false
false
false
false
or1onsli/Fou.run-
MusicRun/BarrierTexture.swift
1
961
// // BarrierTexture.swift // Fou.run() // // Copyright © 2016 Shock&Awe. All rights reserved. // import Foundation import UIKit struct BarrierTexture { static let high: UIImage = #imageLiteral(resourceName: "ostacolo_alto_1") static let low: UIImage = #imageLiteral(resourceName: "ostacolo_basso_1") static let medium: UIImage = #imageLiteral(resourceName: "ostacolo_medio") static let highBarrierAnimation: [UIImage] = [#imageLiteral(resourceName: "ostacolo_alto_1"), #imageLiteral(resourceName: "ostacolo_alto_2"), #imageLiteral(resourceName: "ostacolo_alto_3")] static let lowBarrierAnimation: [UIImage] = [#imageLiteral(resourceName: "ostacolo_basso_1"), #imageLiteral(resourceName: "ostacolo_basso_2"), #imageLiteral(resourceName: "ostacolo_basso_3")] }
mit
31659fe3851f8aabffb326ceb653f360
42.636364
97
0.603125
4.528302
false
false
false
false
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtlocation/src/3rdparty/mapbox-gl-native/platform/darwin/test/MGLStyleValueTests.swift
1
1678
import XCTest import Mapbox extension MGLStyleValueTests { func testConstantValues() { let shapeSource = MGLShapeSource(identifier: "test", shape: nil, options: nil) let symbolStyleLayer = MGLSymbolStyleLayer(identifier: "test", source: shapeSource) // Boolean symbolStyleLayer.iconAllowsOverlap = MGLStyleConstantValue(rawValue: true) XCTAssertEqual((symbolStyleLayer.iconAllowsOverlap as! MGLStyleConstantValue<NSNumber>).rawValue, true) // Number symbolStyleLayer.iconHaloWidth = MGLStyleConstantValue(rawValue: 3) XCTAssertEqual((symbolStyleLayer.iconHaloWidth as! MGLStyleConstantValue<NSNumber>).rawValue, 3) // String symbolStyleLayer.text = MGLStyleConstantValue(rawValue: "{name}") XCTAssertEqual((symbolStyleLayer.text as! MGLStyleConstantValue<NSString>).rawValue, "{name}") } func testFunctions() { let shapeSource = MGLShapeSource(identifier: "test", shape: nil, options: nil) let symbolStyleLayer = MGLSymbolStyleLayer(identifier: "test", source: shapeSource) // Boolean let stops: [NSNumber: MGLStyleValue<NSNumber>] = [ 1: MGLStyleValue(rawValue: true), 2: MGLStyleValue(rawValue: false), 3: MGLStyleValue(rawValue: true), 4: MGLStyleValue(rawValue: false), ] symbolStyleLayer.iconAllowsOverlap = MGLStyleFunction<NSNumber>(interpolationBase: 1, stops: stops) XCTAssertEqual((symbolStyleLayer.iconAllowsOverlap as! MGLStyleFunction<NSNumber>), MGLStyleFunction(interpolationBase: 1, stops: stops)) } }
gpl-3.0
f1300efb60c2cfafd644ed0477680979
43.157895
145
0.683552
5.343949
false
true
false
false
pointfreeco/combine-schedulers
Sources/CombineSchedulers/UIScheduler.swift
1
2565
#if canImport(Combine) import Combine import Dispatch /// A scheduler that executes its work on the main queue as soon as possible. /// /// This scheduler is inspired by the /// [equivalent](https://github.com/ReactiveCocoa/ReactiveSwift/blob/58d92aa01081301549c48a4049e215210f650d07/Sources/Scheduler.swift#L92) /// scheduler in the [ReactiveSwift](https://github.com/ReactiveCocoa/ReactiveSwift) project. /// /// If `UIScheduler.shared.schedule` is invoked from the main thread then the unit of work will be /// performed immediately. This is in contrast to `DispatchQueue.main.schedule`, which will incur /// a thread hop before executing since it uses `DispatchQueue.main.async` under the hood. /// /// This scheduler can be useful for situations where you need work executed as quickly as /// possible on the main thread, and for which a thread hop would be problematic, such as when /// performing animations. public struct UIScheduler: Scheduler, Sendable { public typealias SchedulerOptions = Never public typealias SchedulerTimeType = DispatchQueue.SchedulerTimeType /// The shared instance of the UI scheduler. /// /// You cannot create instances of the UI scheduler yourself. Use only the shared instance. public static let shared = Self() public var now: SchedulerTimeType { DispatchQueue.main.now } public var minimumTolerance: SchedulerTimeType.Stride { DispatchQueue.main.minimumTolerance } public func schedule(options: SchedulerOptions? = nil, _ action: @escaping () -> Void) { if DispatchQueue.getSpecific(key: key) == value { action() } else { DispatchQueue.main.schedule(action) } } public func schedule( after date: SchedulerTimeType, tolerance: SchedulerTimeType.Stride, options: SchedulerOptions? = nil, _ action: @escaping () -> Void ) { DispatchQueue.main.schedule(after: date, tolerance: tolerance, options: nil, action) } public func schedule( after date: SchedulerTimeType, interval: SchedulerTimeType.Stride, tolerance: SchedulerTimeType.Stride, options: SchedulerOptions? = nil, _ action: @escaping () -> Void ) -> Cancellable { DispatchQueue.main.schedule( after: date, interval: interval, tolerance: tolerance, options: nil, action ) } private init() { DispatchQueue.main.setSpecific(key: key, value: value) } } private let key = DispatchSpecificKey<UInt8>() private let value: UInt8 = 0 #endif
mit
a7c17f94dfa153ed64f8f09cea21fc66
37.863636
140
0.702144
4.638336
false
false
false
false
hejunbinlan/GRDB.swift
GRDB/Core/Statement.swift
1
4810
/// A nicer name than COpaquePointer for SQLite statement handle typealias SQLiteStatement = COpaquePointer private let SQLITE_TRANSIENT = unsafeBitCast(COpaquePointer(bitPattern: -1), sqlite3_destructor_type.self) /** A statement represents a SQL query. It is the base class of UpdateStatement that executes *update statements*, and SelectStatement that fetches rows. */ public class Statement { /// The SQL query public var sql: String /// The query arguments public var arguments: StatementArguments? { didSet { reset() // necessary before applying new arguments clearArguments() if let arguments = arguments { arguments.bindInStatement(self) } } } // MARK: - Not public /// The database let database: Database /// The SQLite statement handle let sqliteStatement: SQLiteStatement init(database: Database, sql: String) throws { database.assertValid() // See https://www.sqlite.org/c3ref/prepare.html let sqlCodeUnits = sql.nulTerminatedUTF8 var sqliteStatement: SQLiteStatement = nil var consumedCharactersCount: Int = 0 var code: Int32 = 0 sqlCodeUnits.withUnsafeBufferPointer { codeUnits in let sqlHead = UnsafePointer<Int8>(codeUnits.baseAddress) var sqlTail: UnsafePointer<Int8> = nil code = sqlite3_prepare_v2(database.sqliteConnection, sqlHead, -1, &sqliteStatement, &sqlTail) consumedCharactersCount = sqlTail - sqlHead + 1 } self.database = database self.sql = sql self.sqliteStatement = sqliteStatement switch code { case SQLITE_OK: guard consumedCharactersCount == sqlCodeUnits.count else { fatalError("Invalid SQL string: multiple statements found. To execute multiple statements, use Database.executeMultiStatement() instead.") } default: throw DatabaseError(code: code, message: database.lastErrorMessage, sql: sql) } } deinit { if sqliteStatement != nil { sqlite3_finalize(sqliteStatement) } } // Exposed for StatementArguments. Don't make this one public unless we keep the arguments property in sync. final func bind(value: DatabaseValueConvertible?, atIndex index: Int) { let databaseValue = value?.databaseValue ?? .Null let code: Int32 switch databaseValue { case .Null: code = sqlite3_bind_null(sqliteStatement, Int32(index)) case .Integer(let int64): code = sqlite3_bind_int64(sqliteStatement, Int32(index), int64) case .Real(let double): code = sqlite3_bind_double(sqliteStatement, Int32(index), double) case .Text(let text): code = sqlite3_bind_text(sqliteStatement, Int32(index), text, -1, SQLITE_TRANSIENT) case .Blob(let blob): let data = blob.data code = sqlite3_bind_blob(sqliteStatement, Int32(index), data.bytes, Int32(data.length), SQLITE_TRANSIENT) } if code != SQLITE_OK { fatalError(DatabaseError(code: code, message: database.lastErrorMessage, sql: sql).description) } } // Exposed for StatementArguments. Don't make this one public unless we keep the arguments property in sync. final func bind(value: DatabaseValueConvertible?, forKey key: String) { let index = Int(sqlite3_bind_parameter_index(sqliteStatement, ":\(key)")) guard index > 0 else { fatalError("Key not found in SQLite statement: `:\(key)`") } bind(value, atIndex: index) } // Not public until a need for it. final func reset() { let code = sqlite3_reset(sqliteStatement) if code != SQLITE_OK { fatalError(DatabaseError(code: code, message: database.lastErrorMessage, sql: sql).description) } } // Don't make this one public or internal unless we keep the arguments property in sync. private func clearArguments() { let code = sqlite3_clear_bindings(sqliteStatement) if code != SQLITE_OK { fatalError(DatabaseError(code: code, message: database.lastErrorMessage, sql: sql).description) } } } // MARK: - SQLite identifier quoting extension String { /** Returns the receiver, quoted for safe insertion as an identifier in an SQL query. db.execute("SELECT * FROM \(tableName.quotedDatabaseIdentifier)") */ public var quotedDatabaseIdentifier: String { // See https://www.sqlite.org/lang_keywords.html return "\"\(self)\"" } }
mit
59425e3e43a318731a6b7e117e89a719
34.367647
154
0.630146
4.873354
false
true
false
false
xingerdayu/dayu
dayu/MessageViewController.swift
1
8193
// // MessageViewController.swift // dayu // // Created by Xinger on 15/9/9. // Copyright (c) 2015年 Xinger. All rights reserved. // import UIKit class MessageViewController: BaseUIViewController, UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate { //var app = UIApplication.sharedApplication().delegate as! AppDelegate @IBOutlet weak var myTableView: UITableView! var messageList = NSMutableArray() var groupMessage:Message! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.automaticallyAdjustsScrollViewInsets = false getUserMessages() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messageList.count } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let m_message = messageList[indexPath.row] as! Message switch m_message.msgType { case MessageType.JOIN_GROUP: groupMessage = m_message if m_message.isHandle { ViewUtil.showToast(self.view, text: "您已经处理过该消息", afterDelay: 2) } else { let alertView = UIAlertView(title: "是否同意\(m_message.username)加入该圈子?", message: "", delegate: self, cancelButtonTitle: "取消", otherButtonTitles: "确定") alertView.show() } case MessageType.ADJUST: print("Adjust \(m_message.attachId)") let params = ["cid": m_message.attachId] HttpUtil.post(URLConstants.getCombinationInfoUrl, params: params, success: {(response:AnyObject!) in //print(response) let comb = Comb() comb.parse(response["combinations"] as! NSDictionary) let usb = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) let vc = usb.instantiateViewControllerWithIdentifier("CombDetailViewController") as! CombDetailViewController vc.comb = comb self.navigationController?.pushViewController(vc, animated: true) }) case MessageType.SYSTEM: //TODO 处理系统消息 print("系统消息") default: let topicId = m_message.attachId toTopicActivity(topicId) } } func toTopicActivity(topicId:Int) { let params = ["token":app.getToken(), "id":topicId] HttpUtil.post(URLConstants.getTopicUrl, params: params, success: {(response:AnyObject!) in let topic = Topic.parseTopic(response["topic"] as! NSDictionary) let usb = UIStoryboard(name: "Group", bundle: NSBundle.mainBundle()) let replyVc = usb.instantiateViewControllerWithIdentifier("ReplyListControllerUI") as! ReplyListViewController replyVc.topic = topic self.navigationController?.pushViewController(replyVc, animated: true) }) } func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { if buttonIndex == 1 { let params = ["token":app.getToken(), "userId":groupMessage.sendId, "groupId":groupMessage.attachId] HttpUtil.post(URLConstants.agreeJoinGroupUrl, params: params, success: {(response:AnyObject!) in self.groupMessage.isHandle = true ViewUtil.showToast(self.view, text: "已同意\(self.groupMessage.username)加入该圈子", afterDelay: 2) }, failure: {(error:NSError!) in print(error.description) }, resultError: {(errorCode:String, errorText:String) in ViewUtil.showToast(self.view, text: "已处理过该消息", afterDelay: 2) }) } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("MessageCell", forIndexPath: indexPath) as UITableViewCell let m_message = messageList[indexPath.row] as! Message let bgView = cell.viewWithTag(50)! let photoIv = cell.viewWithTag(51) as! UIImageView let nameLabel = cell.viewWithTag(52) as! UILabel let timeLabel = cell.viewWithTag(53) as! UILabel let titleLabel = cell.viewWithTag(54) as! UILabel let contentLabel = cell.viewWithTag(55) as! UILabel photoIv.clipsToBounds = true photoIv.layer.cornerRadius = 20 photoIv.sd_setImageWithURL(NSURL(string: URLConstants.getUserPhotoUrl(m_message.sendId)), placeholderImage:UIImage(named: "user_default_photo.png")) nameLabel.text = m_message.username timeLabel.text = StringUtil.fitFormatTime(m_message.createTime) titleLabel.text = m_message.title contentLabel.text = m_message.content //contentLabel.translatesAutoresizingMaskIntoConstraints = true //清除 AutoLayout的影响 //bgView.translatesAutoresizingMaskIntoConstraints = true //清除 AutoLayout的影响 let clWidth = 280 * app.autoSizeScaleX let size = m_message.content.textSizeWithFont(UIFont.systemFontOfSize(FONT_SIZE), constrainedToSize: CGSizeMake(clWidth, 20000)); let frame = contentLabel.frame contentLabel.frame = CGRectMake(10 * app.autoSizeScaleX, frame.origin.y, clWidth, size.height) bgView.frame = CGRectMake(10 * app.autoSizeScaleX, bgView.frame.origin.y, 300 * app.autoSizeScaleX, 95 + size.height) return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let m_message = messageList[indexPath.row] as! Message let size = m_message.content.textSizeWithFont(UIFont.systemFontOfSize(FONT_SIZE), constrainedToSize: CGSizeMake(280 * app.autoSizeScaleX, 20000)); return 105 + size.height } func getUserMessages() { let params = ["token": app.getToken(), "readStat": 2] HttpUtil.post(URLConstants.getMessagesUrl, params: params, success: {(response:AnyObject!) in //println(response) if response["stat"] as! String == "OK" { var count = 0 let array = response["messages"] as! NSArray //var list = NSMutableArray() for item in array { let message = Message.parseMessage(item as! NSDictionary) self.messageList.addObject(message) //这里的消息可能以后要存入数据库 if message.status == 0 { count++ //计算未读消息的记录 } } self.myTableView.reloadData() } }) } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { tableView.setEditing(false, animated: true) let msg = messageList[indexPath.row] as! Message deleteMessage(msg) } func deleteMessage(msg:Message) { let params = ["token":app.getToken(), "msgId":msg.id] HttpUtil.post(URLConstants.deleteMessageUrl, params: params, success: {(response:AnyObject!) in self.messageList.removeObject(msg) self.myTableView.reloadData() }) } func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } //设置滑动出来的样式,还有Insert func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return UITableViewCellEditingStyle.Delete } func tableView(tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndexPath indexPath: NSIndexPath) -> String? { return "删除" } }
bsd-3-clause
c533ae530b8de25221d26e4e07c77218
43.21547
164
0.637386
5.042848
false
false
false
false
xwu/swift
test/Constraints/construction.swift
1
6460
// RUN: %target-typecheck-verify-swift struct X { var i : Int, j : Int } struct Y { init (_ x : Int, _ y : Float, _ z : String) {} } enum Z { case none case char(UnicodeScalar) case string(String) case point(Int, Int) init() { self = .none } init(_ c: UnicodeScalar) { self = .char(c) } // expected-note@-1 2 {{candidate expects value of type 'UnicodeScalar' (aka 'Unicode.Scalar') for parameter #1 (got 'Z')}} init(_ s: String) { self = .string(s) } // expected-note@-1 2 {{candidate expects value of type 'String' for parameter #1 (got 'Z')}} init(_ x: Int, _ y: Int) { self = .point(x, y) } } enum Optional<T> { case none case value(T) init() { self = .none } init(_ t: T) { self = .value(t) } } class Base { } class Derived : Base { } var d : Derived typealias Point = (x : Int, y : Int) var hello : String = "hello"; var world : String = "world"; var i : Int var z : Z = .none func acceptZ(_ z: Z) {} func acceptString(_ s: String) {} Point(1, 2) // expected-warning {{expression of type '(x: Int, y: Int)' is unused}} var db : Base = d X(i: 1, j: 2) // expected-warning{{unused}} Y(1, 2, "hello") // expected-warning{{unused}} // Unions Z(UnicodeScalar("a")) // expected-warning{{unused}} Z(1, 2) // expected-warning{{unused}} acceptZ(.none) acceptZ(.char("a")) acceptString("\(hello), \(world) #\(i)!") Optional<Int>(1) // expected-warning{{unused}} Optional(1) // expected-warning{{unused}} _ = .none as Optional<Int> Optional(.none) // expected-error {{cannot infer contextual base in reference to member 'none'}} // Interpolation _ = "\(hello), \(world) #\(i)!" class File { init() { fd = 0 body = "" } var fd : Int32, body : String func replPrint() { print("File{\n fd=\(fd)\n body=\"\(body)\"\n}", terminator: "") } } // Non-trivial references to metatypes. struct Foo { struct Inner { } } extension Foo { func getInner() -> Inner { return Inner() } } // Downcasting var b : Base _ = b as! Derived // Construction doesn't permit conversion. // NOTE: Int and other integer-literal convertible types // are special cased in the library. Int(i) // expected-warning{{unused}} _ = i as Int Z(z) // expected-error{{no exact matches in call to initializer}} Z.init(z) // expected-error {{no exact matches in call to initializer}} _ = z as Z // Construction from inouts. struct FooRef { } struct BarRef { init(x: inout FooRef) {} init(x: inout Int) {} } var f = FooRef() var x = 0 BarRef(x: &f) // expected-warning{{unused}} BarRef(x: &x) // expected-warning{{unused}} // Construction from a Type value not immediately resolved. struct S1 { init(i: Int) { } } struct S2 { init(i: Int) { } } func getMetatype(_ i: Int) -> S1.Type { return S1.self } func getMetatype(_ d: Double) -> S2.Type { return S2.self } var s1 = getMetatype(1).init(i: 5) s1 = S1(i: 5) var s2 = getMetatype(3.14).init(i: 5) s2 = S2(i: 5) // rdar://problem/19254404 let i32 = Int32(123123123) Int(i32 - 2 + 1) // expected-warning{{unused}} // rdar://problem/19459079 let xx: UInt64 = 100 let yy = ((xx + 10) - 5) / 5 let zy = (xx + (10 - 5)) / 5 // rdar://problem/30588177 struct S3 { init() { } } let s3a = S3() extension S3 { init?(maybe: S3) { return nil } } let s3b = S3(maybe: s3a) // SR-5245 - Erroneous diagnostic - Type of expression is ambiguous without more context class SR_5245 { struct S { enum E { case e1 case e2 } let e: [E] } init(s: S) {} } SR_5245(s: SR_5245.S(f: [.e1, .e2])) // expected-error@-1 {{incorrect argument label in call (have 'f:', expected 'e:')}} {{22-23=e}} // rdar://problem/34670592 - Compiler crash on heterogeneous collection literal _ = Array([1, "hello"]) // Ok func init_via_non_const_metatype(_ s1: S1.Type) { _ = s1(i: 42) // expected-error {{initializing from a metatype value must reference 'init' explicitly}} {{9-9=.init}} _ = s1.init(i: 42) // ok } // rdar://problem/45535925 - diagnostic is attached to invalid source location func rdar_45535925() { struct S { var addr: String var port: Int private init(addr: String, port: Int?) { // expected-note@-1 {{'init(addr:port:)' declared here}} self.addr = addr self.port = port ?? 31337 } private init(port: Int) { self.addr = "localhost" self.port = port } private func foo(_: Int) {} // expected-note {{'foo' declared here}} private static func bar() {} // expected-note {{'bar()' declared here}} } _ = S(addr: "localhost", port: nil) // expected-error@-1 {{'S' initializer is inaccessible due to 'private' protection level}} func baz(_ s: S) { s.foo(42) // expected-error@-1 {{'foo' is inaccessible due to 'private' protection level}} S.bar() // expected-error@-1 {{'bar' is inaccessible due to 'private' protection level}} } } // rdar://problem/50668864 func rdar_50668864() { struct Foo { init(anchors: [Int]) { // expected-note {{'init(anchors:)' declared here}} self = .init { _ in [] } // expected-error {{trailing closure passed to parameter of type '[Int]' that does not accept a closure}} } } } // SR-10837 (rdar://problem/51442825) - init partial application regression func sr_10837() { struct S { let value: Int static func foo(_ v: Int?) { _ = v.flatMap(self.init(value:)) // Ok _ = v.flatMap(S.init(value:)) // Ok _ = v.flatMap { S.init(value:)($0) } // Ok _ = v.flatMap { self.init(value:)($0) } // Ok } } class A { init(bar: Int) {} } class B : A { init(value: Int) {} convenience init(foo: Int = 42) { self.init(value:)(foo) // Ok self.init(value:) // expected-error@-1 {{cannot reference 'self.init' initializer delegation as function value}} } } class C : A { override init(bar: Int) { super.init(bar:)(bar) // Ok super.init(bar:) // expected-error@-1 {{cannot reference 'super.init' initializer chain as function value}} } } } // To make sure that hack related to type variable bindings works as expected we need to test // that in the following case result of a call to `reduce` maintains optionality. func test_that_optionality_of_closure_result_is_preserved() { struct S {} let arr: [S?] = [] let _: [S]? = arr.reduce([], { (a: [S]?, s: S?) -> [S]? in a.flatMap { (group: [S]) -> [S]? in s.map { group + [$0] } } // Ok }) }
apache-2.0
13cc28e48686fdc8f280fc41be474856
23.285714
136
0.601084
3.117761
false
false
false
false
jaredsinclair/sodes-audio-example
Sodes/SodesAudio/ByteRange.swift
1
4111
// // ByteRange.swift // SodesAudio // // Created by Jared Sinclair on 7/24/16. // // import Foundation protocol Summable: Comparable { static func +(lhs: Self, rhs: Self) -> Self static func -(lhs: Self, rhs: Self) -> Self func decremented() -> Self func toInt() -> Int } extension Int64: Summable { func decremented() -> Int64 { return self - 1 } func toInt() -> Int { return Int(self) } } public typealias ByteRange = Range<Int64> enum ByteRangeIndexPosition { case before case inside case after } extension Range where Bound: Summable { var length: Bound { return upperBound - lowerBound } var lastValidIndex: Bound { return upperBound.decremented() } var subdataRange: Range<Int> { return lowerBound.toInt()..<(upperBound.toInt()) } func leadingIntersection(in otherRange: Range) -> Range? { if lowerBound <= otherRange.lowerBound && lastValidIndex >= otherRange.lowerBound { if lastValidIndex > otherRange.lastValidIndex { return otherRange } else { let lowerBound = otherRange.lowerBound let upperBound = otherRange.lowerBound + length - otherRange.lowerBound return (lowerBound..<upperBound) } } else { return nil } } func trailingRange(in otherRange: Range) -> Range? { if let leading = leadingIntersection(in: otherRange), !fullySatisfies(otherRange) { return ((otherRange.lowerBound + leading.length)..<otherRange.upperBound) } else { return nil } } func fullySatisfies(_ requestedRange: Range) -> Bool { if let intersection = leadingIntersection(in: requestedRange) { return intersection == requestedRange } else { return false } } func intersects(_ otherRange: Range) -> Bool { return otherRange.lowerBound < upperBound && lowerBound < otherRange.upperBound } func isContiguousWith(_ otherRange: Range) -> Bool { if otherRange.upperBound == lowerBound { return true } else if upperBound == otherRange.lowerBound { return true } else { return false } } func relativePosition(of index: Bound) -> ByteRangeIndexPosition { if index < lowerBound { return .before } else if index >= upperBound { return .after } else { return .inside } } } func combine(_ ranges: [ByteRange]) -> [ByteRange] { var combinedRanges = [ByteRange]() let uncheckedRanges = ranges.sorted{$0.length > $1.length} for uncheckedRange in uncheckedRanges { let intersectingRanges = combinedRanges.filter{ $0.intersects(uncheckedRange) || $0.isContiguousWith(uncheckedRange) } if intersectingRanges.isEmpty { combinedRanges.append(uncheckedRange) } else { for range in intersectingRanges { if let index = combinedRanges.index(of: range) { combinedRanges.remove(at: index) } } let combinedRange = intersectingRanges.reduce(uncheckedRange, +) combinedRanges.append(combinedRange) } } return combinedRanges.sorted{$0.lowerBound < $1.lowerBound} } /// Adding byte ranges is currently very naive. It takes the lowest lowerBound /// and the highest upper bound and computes a range between the two. It assumes /// that the programmer desires this behavior, for instance, when you're adding /// a sequence of byte ranges which form a continuous range when summed as a /// whole even though any two random members might not overlap or be contiguous. private func +(lhs: ByteRange, rhs: ByteRange) -> ByteRange { let lowerBound = min(lhs.lowerBound, rhs.lowerBound) let upperBound = max(lhs.upperBound, rhs.upperBound) return (lowerBound..<upperBound) }
mit
d82af754bebbae886844ede35ab4158e
29.227941
91
0.610557
4.813817
false
false
false
false
krevis/MIDIApps
Applications/SysExLibrarian/RecordManyController.swift
1
2425
/* Copyright (c) 2002-2021, Kurt Revis. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. */ import Cocoa class RecordManyController: RecordController { // MARK: RecordController subclass override var nibName: String { "RecordMany" } override func tellMIDIControllerToStartRecording() { midiController?.listenForMultipleMessages() } override func updateIndicators(status: MIDIController.MessageListenStatus) { if status.bytesRead == 0 { progressMessageField.stringValue = waitingForSysexMessage progressBytesField.stringValue = "" } else { progressMessageField.stringValue = receivingSysexMessage progressBytesField.stringValue = String.abbreviatedByteCount(status.bytesRead) } let hasAtLeastOneCompleteMessage = status.messageCount > 0 if hasAtLeastOneCompleteMessage { let format = status.messageCount > 1 ? Self.totalProgressPluralFormatString : Self.totalProgressFormatString totalProgressField.stringValue = String(format: format, status.messageCount, String.abbreviatedByteCount(status.totalBytesRead)) doneButton.isEnabled = true } else { totalProgressField.stringValue = "" doneButton.isEnabled = false } } // MARK: Actions @IBAction func doneRecording(_ sender: Any?) { midiController?.doneWithMultipleMessageListen() stopObservingMIDIController() progressIndicator.stopAnimation(nil) mainWindowController?.window?.endSheet(sheetWindow) mainWindowController?.addReadMessagesToLibrary() } // MARK: Private @IBOutlet private var totalProgressField: NSTextField! @IBOutlet private var doneButton: NSButton! static private var totalProgressFormatString = NSLocalizedString("Total: %d message, %@", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "format of progress message when receiving multiple sysex messages (one message so far)") static private var totalProgressPluralFormatString = NSLocalizedString("Total: %d messages, %@", tableName: "SysExLibrarian", bundle: Bundle.main, comment: "format of progress message when receiving multiple sysex messages (more than one message so far)") }
bsd-3-clause
39327ca956f3935c45385760abb4c487
36.307692
259
0.71134
5.365044
false
false
false
false
chenjs/Programming-iOS9-VCDemos
NibInstantiatedVC/NibInstantiatedVC/RootViewController.swift
1
1078
// // RootViewController.swift // NibInstantiatedVC // // Created by chenjs on 16/1/17. // Copyright © 2016年 chenjs. All rights reserved. // import UIKit class RootViewController: UIViewController { // remark the following method, let UIViewController's default loadView() automatically create a general view // override func loadView() { // let v = UIView() // self.view = v // } // override func viewDidLoad() { // super.viewDidLoad() // // assert(viewIfLoaded != nil) // assert(isViewLoaded()) // // self.view.backgroundColor = UIColor.greenColor() // let label = UILabel() // label.text = "Hello World!" // self.view.addSubview(label) // label.translatesAutoresizingMaskIntoConstraints = false // NSLayoutConstraint.activateConstraints([ // label.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor), // label.centerYAnchor.constraintEqualToAnchor(self.view.centerYAnchor) // ]) // } }
mit
5f72d85eb252db5023c229051670cb4d
28.861111
113
0.618605
4.479167
false
false
false
false
jiazifa/SSFormSwift
SSFormSwift/Controller/SSFormTableViewSourceHelper.swift
1
10228
// // SSFormTableViewSourceHelper.swift // AnAnOrderCarDriver // // Created by Mac on 17/3/29. // Copyright © 2017年 treee. All rights reserved. // import Foundation import UIKit ///将用到的代理和数据源等剥离出来 open class SSFormTableViewSourceHelper: NSObject, UITableViewDelegate, UITableViewDataSource, SSFormDescriptorDelegate { //MARK:- //MARK:properties public var form:SSFormDescriptor! { didSet { form.delegate = self } } public var tableView:UITableView! //MARK:- //MARK:init public convenience init(_ tableView:UITableView) { self.init() self.tableView = tableView self.tableView.delegate = self self.tableView.dataSource = self self.form = SSFormDescriptor.init() self.form.delegate = self } public convenience init(_ tableView:UITableView, form: SSFormDescriptor) { self.init() self.tableView = tableView self.tableView.delegate = self self.tableView.dataSource = self self.form = form self.form.delegate = self } //MARK:- //MARK:dataSource public func numberOfSections(in tableView: UITableView) -> Int { if self.form.formSectionCount != 0 { return self.form.formSectionCount } return 1 } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { print("numberOfRowsInSection") assert(section <= (self.form.formSectionCount), "out of range") let section:SSFormSectionDescriptor = self.form.formSectionAt(section) return section.formRowsCount } public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { print("heightForHeaderInSection") assert(section <= (self.form.formSectionCount), "out of range") let section:SSFormSectionDescriptor = self.form.formSectionAt(section) return (section.height > 0) ? section.height : 0.01 } public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { print("heightForFooterInSection") return 0.01 } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { print("heightForRowAt\(indexPath)") assert(indexPath.section <= (self.form.formSectionCount), "out of range") let section:SSFormSectionDescriptor = self.form.formSectionAt(indexPath.section) let formRow:SSFormRowDescriptor = section[indexPath.row] return formRow.height } public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { print("titleForHeaderInSection") assert(section <= (self.form.formSectionCount), "out of range") let section:SSFormSectionDescriptor = self.form.formSectionAt(section) return section.title } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { print("cellForRowAt\(indexPath)") guard let rowDescriptor:SSFormRowDescriptor = self.form[indexPath] else { return UITableViewCell.init() } let cell:SSFormBaseCell cell = rowDescriptor.makeCell(tableView)! cell.rowDescriptor = rowDescriptor cell.update() return cell } public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { guard let formRow:SSFormRowDescriptor = form[indexPath] else { return false} print("canEditRowAt\(formRow.canEditRow)") return formRow.canEditRow } public func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { guard let formRow:SSFormRowDescriptor = form[indexPath] else { return false} print("--->canMoveRowAt\(formRow.canMoveRow)") return formRow.canMoveRow } //编辑样式,如果想要使用滑动显示侧滑菜单,那么需要删除这个方法 public func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle { guard let formRow:SSFormRowDescriptor = form[indexPath] else { return .none} print("editingStyleForRowAt--->\(formRow.editingStyle)") return formRow.editingStyle } //MARK:- //MARK:delegate public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { print("didSelectRowAt\(indexPath)") let cell:SSFormBaseCell = tableView.cellForRow(at: indexPath) as! SSFormBaseCell guard cell.rowDescriptor != nil else { return} let formRow:SSFormRowDescriptor = cell.rowDescriptor! if ((formRow.onClickedBlock) != nil) { formRow.onClickedBlock!(formRow,indexPath) } } ///编辑状态下的代理方法 public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { guard let formRow:SSFormRowDescriptor = form[indexPath] else { return} print("commit editingStyle") if formRow.editingStyleHandle != nil { formRow.editingStyleHandle!(formRow, editingStyle, indexPath) }else { switch editingStyle { case .none: break case .insert: guard let addRow:SSFormRowDescriptor = formRow.addFormRow else { break} guard let index = formRow.sectionDescriptor?.rowIndexOf(formRow) else { break} formRow.sectionDescriptor?.add(addRow, At: index + 1) break case .delete: formRow.removeFromSection() break } } } ///删除按钮的文字 public func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? { let cell:SSFormBaseCell = tableView.cellForRow(at: indexPath) as! SSFormBaseCell guard cell.rowDescriptor != nil else { return nil} return cell.rowDescriptor?.titleForDeleteConfirmationButton } /* ///编辑状态下侧滑返回的几个响应的集合,如果想要执行这个方法,那么必须将editingStyleForRowAt方法删除掉 func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { print("editActionsForRowAt") let cell:SSFormBaseCell = tableView.cellForRow(at: indexPath) as! SSFormBaseCell guard cell.rowDescriptor != nil else { return nil} return cell.rowDescriptor?.editActions } */ /// 移动的代理方法 public func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) { form.exchangeFormRow(sourceIndexPath, to: destinationIndexPath) } //MARK:- //MARK:formDescriptorDelegate public func formRowHasBeenAdded(_ formRow: SSFormRowDescriptor, At indexPath: IndexPath) { print("formRowHasBeenAdded\(indexPath)") self.tableView.beginUpdates() self.tableView.insertRows(at: [indexPath], with: insertFormRow(formRow)) self.tableView.endUpdates() } public func formRowHasBeenRemoced(_ formRow: SSFormRowDescriptor, At indexPath: IndexPath) { print("formRowHasBeenRemoced\(indexPath)") self.tableView.beginUpdates() self.tableView.deleteRows(at: [indexPath], with: deleteFormRow(formRow)) self.tableView.endUpdates() } public func formSectionHasBeenAdded(_ formSection: SSFormSectionDescriptor, At index:Int) { print("formSectionHasBeenAdded") self.tableView.beginUpdates() self.tableView.insertSections(IndexSet.init(integer: index), with: insertFormSection(formSection)) self.tableView.endUpdates() } public func formSectionHasBeenRemoved(_ formSection: SSFormSectionDescriptor, At index:Int) { print("formSectionHasBeenRemoved") self.tableView.beginUpdates() self.tableView.deleteSections(IndexSet.init(integer: index), with: insertFormSection(formSection)) self.tableView.endUpdates() } public func formRowDescriptorValueHasChanged(_ formRow: SSFormRowDescriptor, newValue: AnyObject) { print("formRowDescriptorValueHasChanged") self.tableView.beginUpdates() self.tableView.reloadRows(at: [form.indexPathOf(formRow)!], with: formRow.freshAnimation) formRow.cell?.update() self.tableView.endUpdates() } //MARK:- //MARK:SSFormViewControllerDelegate func insertFormRow(_ formRow: SSFormRowDescriptor) -> UITableViewRowAnimation { return formRow.insertAnimation } func deleteFormRow(_ formRow: SSFormRowDescriptor) -> UITableViewRowAnimation { return formRow.deleteAnimation } func insertFormSection(_ formSection: SSFormSectionDescriptor) -> UITableViewRowAnimation { return formSection.insertAnimation } func deleteFormSection(_ formSection: SSFormSectionDescriptor) -> UITableViewRowAnimation { return formSection.deleteAnimation } //MARK:- //MARK:helper func update(_ formRow:SSFormRowDescriptor) -> Void { /// 在这里不能放刷新操作,会造成循环引用 guard let cell:SSFormBaseCell = formRow.cell else { return } self.configCell(cell) cell.setNeedsLayout() print("\(cell)\([form.indexPathOf(formRow)!])") } func configCell(_ cell:SSFormBaseCell) -> Void { cell.update() } //MARK:- //MARK:runtime_Helper } private var sourceHelperKey: UInt = 0 extension UITableView { public var sourceHelper: SSFormTableViewSourceHelper? { get { return objc_getAssociatedObject(self, &sourceHelperKey) as? SSFormTableViewSourceHelper } set(newValue) { objc_setAssociatedObject(self, &sourceHelperKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN) } } }
mit
bda42fb1d6b2b5cb7e3b9f2a0a11616f
38.271654
134
0.672381
5.173755
false
false
false
false
gizmosachin/VolumeBar
Sources/Internal/SystemVolumeManager.swift
1
4834
// // SystemVolumeManager.swift // // Copyright (c) 2016-Present Sachin Patel (http://gizmosachin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import AVFoundation @objc internal protocol SystemVolumeObserver { func volumeChanged(to volume: Float) } internal final class SystemVolumeManager: NSObject { fileprivate let observers: NSHashTable<SystemVolumeObserver> fileprivate var isObservingSystemVolumeChanges: Bool = false internal override init() { observers = NSHashTable<SystemVolumeObserver>.weakObjects() super.init() startObservingSystemVolumeChanges() startObservingApplicationStateChanges() } deinit { observers.removeAllObjects() stopObservingSystemVolumeChanges() stopObservingApplicationStateChanges() } public func volumeChanged(to volume: Float) { for case let observer as SystemVolumeObserver in observers.objectEnumerator() { observer.volumeChanged(to: volume) } } } // System Volume Changes internal extension SystemVolumeManager { func startObservingSystemVolumeChanges() { try? AVAudioSession.sharedInstance().setActive(true) if !isObservingSystemVolumeChanges { // Observe system volume changes AVAudioSession.sharedInstance().addObserver(self, forKeyPath: #keyPath(AVAudioSession.outputVolume), options: [.old, .new], context: nil) // We need to manually set this to avoid adding ourselves as an observer twice. // This can happen if VolumeBar is started and the app has just launched. // Without this, KVO retains us and we crash when system volume changes after stop() is called. :( isObservingSystemVolumeChanges = true } } func stopObservingSystemVolumeChanges() { // Stop observing system volume changes if isObservingSystemVolumeChanges { AVAudioSession.sharedInstance().removeObserver(self, forKeyPath: #keyPath(AVAudioSession.outputVolume)) isObservingSystemVolumeChanges = false } } /// Observe changes in volume. /// /// This method is called when the user presses either of the volume buttons. override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { let volume = AVAudioSession.sharedInstance().outputVolume volumeChanged(to: volume) } } // Application State Changes internal extension SystemVolumeManager { func startObservingApplicationStateChanges() { // Add application state observers NotificationCenter.default.addObserver(self, selector: #selector(SystemVolumeManager.applicationWillResignActive(notification:)), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(SystemVolumeManager.applicationDidBecomeActive(notification:)), name: UIApplication.didBecomeActiveNotification, object: nil) } func stopObservingApplicationStateChanges() { // Remove application state observers NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil) } /// Observe when the application background state changes. @objc func applicationWillResignActive(notification: Notification) { // Stop observing volume while in the background stopObservingSystemVolumeChanges() } @objc func applicationDidBecomeActive(notification: Notification) { // Restart session after becoming active startObservingSystemVolumeChanges() } } // Volume Manager Observers internal extension SystemVolumeManager { func addObserver(_ observer: SystemVolumeObserver) { observers.add(observer) } func removeObserver(_ observer: SystemVolumeObserver) { observers.remove(observer) } }
mit
324667827273704d88c880c8ebe72517
37.062992
194
0.779892
4.819541
false
false
false
false
alexfacciorusso/MaterialTwitterClient
MaterialTwitterClient/TwitterApi.swift
1
2297
// // TwitterApi.swift // MaterialTwitterClient // // Created by Alex Facciorusso on 09/03/17. // Copyright © 2017 Alex Facciorusso. All rights reserved. // import Foundation import Swifter import RxSwift import Nuke import NukeToucanPlugin class TwitterApi { static let sharedInstance = { return TwitterApi() }() private let twitterConsumerKey = "YOUR_TWITTER_CONSUMER_KEY" private let twitterConsumerSecret = "YOUR_TWITTER_CONSUMER_SECRET" var isAuthenticated = false private let swifter: Swifter private init() { self.swifter = Swifter(consumerKey: twitterConsumerKey, consumerSecret: twitterConsumerSecret, appOnly: true) } func authorizeApp() -> Observable<Void> { return Observable.create { obs in print("Authorizing app…") self.swifter.authorizeAppOnly(success: { _ in print("Twitter authorization success.") self.isAuthenticated = true obs.onCompleted() }, failure: { err in print("Twitter authorization error.", err) obs.onError(err) }) return Disposables.create() } } func searchForTweets(usingQuery query: String) -> Observable<[Tweet]> { return Observable.create { obs in self.swifter.searchTweet(using: query, count: 100, success: { json, _ in guard let tweetsJson = json.array else { obs.onNext([]) obs.onCompleted() return } let tweets = tweetsJson.map { it -> Tweet in var avatar: URL? = nil if let avatarStr = it["user"]["profile_image_url_https"].string { avatar = URL(string: avatarStr) } return Tweet(id: it["id"].integer!, name: it["user"]["name"].string!, screenName: it["user"]["screen_name"].string!, avatar: avatar, text: it["text"].string!) } obs.onNext(tweets) obs.onCompleted() }, failure: { err in obs.onError(err) }) return Disposables.create() }.observeOn(MainScheduler.instance) } }
apache-2.0
8e93a36752451c649379a089b7b8de7b
33.757576
178
0.558849
4.860169
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/NetworkServices/MVAnalyticsEventNS.swift
1
1248
// // MVAnalyticsEventNS.swift // Pods // // Created by Leonardo Vinicius Kaminski Ferreira on 17/10/18. // import Foundation class MVAnalyticsEventNS: BaseNS { static let shared = MVAnalyticsEventNS() lazy var requester: AwesomeCoreRequester = AwesomeCoreRequester(cacheType: .realm) override init() {} func track(_ event: MVAnalyticsEvent, params: AwesomeCoreNetworkServiceParams, _ response:@escaping (MVAnalyticsIdentifyStatus?, ErrorData?) -> Void) { _ = requester.performRequestAuthorized( ACConstants.shared.mvAnalyticsEventURL, forceUpdate: true, headersParam: ACConstants.shared.analyticsHeadersMV, method: .POST, jsonBody: event.encoded, completion: { (data, error, responseType) in guard let data = data else { response(nil, nil) return } if let error = error { print("Error fetching from API: \(error.message)") response(nil, error) return } let status = MVAnalyticsIdentifyStatusMP.parse(data) response(status, nil) }) } }
mit
a825d5c16a3c45e8587e6b20f4196541
32.72973
208
0.582532
5.093878
false
false
false
false
Shark/GlowingRemote
GlowingRemote/SettingsController.swift
1
1495
// // SettingsController.swift // GlowingRemote // // Created by Felix Seidel on 22/07/15. // Copyright © 2015 Felix Seidel. All rights reserved. // import UIKit import WatchConnectivity class SettingsController: UITableViewController { weak var apiBaseUrlTextField : UITextField? override func viewWillDisappear(animated: Bool) { saveValues() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier("GRBaseURLCell")! let baseUrlField = cell.viewWithTag(1) as! UITextField apiBaseUrlTextField = baseUrlField let delegate = UIApplication.sharedApplication().delegate as! AppDelegate if let baseUrl = delegate.stateManager.apiBaseUrl { baseUrlField.text = baseUrl.absoluteString } return cell } private func saveValues() { if let textValue = apiBaseUrlTextField?.text { let delegate = UIApplication.sharedApplication().delegate as! AppDelegate delegate.stateManager.apiBaseUrl = NSURL(string: textValue) delegate.stateManager.devices = nil } } }
isc
d6dabab1947873142d64b9d8a23df1fb
31.5
118
0.68407
5.413043
false
false
false
false
DonMag/ScratchPad
Swift3/scratchy/XC8.playground/Pages/PageVC2.xcplaygroundpage/Contents.swift
1
5410
import UIKit import PlaygroundSupport class myPage: UIViewController { var theLabel: UILabel? var theText: String = "x" { didSet { theLabel?.text = theText } } var theIDX: Int = 0 init(frame: CGRect) { super.init(nibName: nil, bundle: nil) self.view = UIView(frame: frame) self.view.backgroundColor = UIColor.orange let l = UILabel(frame: frame.insetBy(dx: 20, dy: 20)) l.backgroundColor = UIColor.lightGray self.view.addSubview(l) l.text = theText l.textAlignment = .center theLabel = l } override func viewDidLoad() { super.viewDidLoad() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class myPgVC: UIPageViewController, UIPageViewControllerDataSource { var arrPageTitle = [String]() var pgBackgroundColor = UIColor.orange override func viewDidLoad() { super.viewDidLoad() arrPageTitle = ["A", "B", "C", "D", "E"]; self.dataSource = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.setViewControllers([getViewControllerAtIndex(0)] as [UIViewController], direction: UIPageViewControllerNavigationDirection.forward, animated: false, completion: nil) } func changeBKG(_ toColor: UIColor) { pgBackgroundColor = toColor guard let vcs = self.viewControllers else { return } if vcs.isEmpty { return } if let vc = self.viewControllers?[0] as? myPage { vc.view.backgroundColor = pgBackgroundColor } } func gotoPageByIndex(_ index: Int) { if index < arrPageTitle.count { self.setViewControllers([getViewControllerAtIndex(index)] as [UIViewController], direction: UIPageViewControllerNavigationDirection.forward, animated: false, completion: nil) } } // MARK:- UIPageViewControllerDataSource Methods func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let vc = viewController as? myPage else { return nil } var index: Int = vc.theIDX if ((index == 0) || (index == NSNotFound)) { index = arrPageTitle.count } index -= 1 return getViewControllerAtIndex(index) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { guard let vc = viewController as? myPage else { return nil } var index: Int = vc.theIDX if (index == NSNotFound) { return nil; } index += 1; if (index == arrPageTitle.count) { index = 0 } return getViewControllerAtIndex(index) } // MARK:- Other Methods func getViewControllerAtIndex(_ index: NSInteger) -> UIViewController { let vc = myPage(frame: self.view.bounds) vc.theIDX = index vc.theText = arrPageTitle[index] vc.view.backgroundColor = pgBackgroundColor return vc } } class MyViewController: UIViewController { var vccA: myPgVC? var vccB: myPgVC? init(frame: CGRect) { super.init(nibName: nil, bundle: nil) self.view = UIView(frame: frame) self.view.backgroundColor = UIColor.white vccA = myPgVC(transitionStyle: UIPageViewControllerTransitionStyle.scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal) self.addChildViewController(vccA!) let vvA = vccA!.view vvA?.frame = CGRect(x: 260, y: 20, width: 200, height: 200) // vvA?.isUserInteractionEnabled = false self.view.addSubview(vvA!) vccA?.didMove(toParentViewController: self) vccA?.changeBKG(UIColor.blue) // vccA?.changeBKG(UIColor.green) // // vccB = myPgVC(transitionStyle: UIPageViewControllerTransitionStyle.scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal) // // self.addChildViewController(vccB!) // // let vvB = vccB!.view // vvB?.frame = CGRect(x: 260, y: 240, width: 200, height: 200) // // self.view.addSubview(vvB!) // // vccB?.didMove(toParentViewController: self) // // vccB?.changeBKG(UIColor.cyan) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addPageVCs() { let vcA = myPgVC(transitionStyle: UIPageViewControllerTransitionStyle.scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal) let vA = vcA.view vA?.frame = CGRect(x: 20, y: 20, width: 200, height: 200) vA?.isUserInteractionEnabled = false self.view.addSubview(vA!) let vcB = myPgVC(transitionStyle: UIPageViewControllerTransitionStyle.scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.horizontal) let vB = vcB.view vB?.frame = CGRect(x: 20, y: 240, width: 200, height: 200) self.view.addSubview(vB!) vcB.changeBKG(UIColor.blue) } } let rootVC = MyViewController(frame: CGRect(x: 0, y: 0, width: 600, height: 600)) //let p = myPage(frame: CGRect(x: 260, y: 20, width: 200, height: 200)) //rootVC.addChildViewController(p) //p.view.backgroundColor = UIColor.purple //rootVC.view.addSubview(p.view) PlaygroundPage.current.liveView = rootVC.view //let container = UIView(frame: CGRect(x: 0, y: 0, width: 600, height: 400)) //// //container.backgroundColor = UIColor.green // // //PlaygroundPage.current.liveView = container //PlaygroundPage.current.needsIndefiniteExecution = true
mit
ccf74c519126ba851546fba40fae1e73
21.827004
177
0.709057
3.783217
false
false
false
false
FengDeng/RXGitHub
RxGitHubAPI/RxGitHubAPI+Parameters.swift
1
2098
// // YYGitHubApi+Parameters.swift // RxGitHub // // Created by 邓锋 on 16/1/25. // Copyright © 2016年 fengdeng. All rights reserved. // import Foundation /** Can be one of all, public, or private. Default: all */ public enum YYVisibility : String{ case All = "all" case Public = "public" case Private = "private" } /** Comma-separated list of values. Can include: * owner: Repositories that are owned by the authenticated user. * collaborator: Repositories that the user has been added to as a collaborator. * organization_member: Repositories that the user has access to through being a member of an organization. This includes every repository on every team that the user is on. Default: owner,collaborator,organization_member */ public enum YYAffiliation : String{ case Owner = "owner" case Collaborator = "collaborator" case Organization_member = "organization_member" case Owner_Collaborator = "owner,collaborator" case Owner_Organization_member = "owner,organization_member" case Collaborator_Organization_member = "collaborator,organization_member" case Owner_Collaborator_Organization_member = "owner,collaborator,organization_member" } /** Can be one of all, owner, public, private, member. Default: all Will cause a 422 error if used in the same request as visibility or affiliation. */ public enum YYType : String{ case All = "all" case Owner = "owner" case Public = "public" case Private = "private" case Member = "member" } /** Can be one of created, updated, pushed, full_name. Default: full_name */ public enum YYSort : String{ case Created = "created" case Updated = "updated" case Pushed = "pushed" case Full_name = "full_name" } /** Can be one of asc or desc. Default: desc */ public enum YYDirection : String{ case Asc = "asc" case Desc = "desc" } //One of created (when the repository was starred) or updated (when it was last pushed to). Default: created public enum YYStarSort : String{ case Created = "created" case Updated = "updated" }
mit
ecc59d8d4bac76a9c59ad39702542515
23.6
173
0.7011
3.879406
false
false
false
false
didinozka/Projekt_Bakalarka
bp_v1/ViewController.swift
1
12752
// // ViewController.swift // bp_v1 // // Created by Dusan Drabik on 17/03/16. // Copyright © 2016 Dusan Drabik. All rights reserved. // import UIKit import CoreBluetooth import CoreLocation import Alamofire class ViewController: UIViewController, DataInitializerDelegate, BeaconDetectorDelegate, CLLocationManagerDelegate, UITableViewDelegate, UITableViewDataSource { private var _beaconDetector: BeaconFinder! private var _bluetoothDetector: BeaconBluetoothDiscovery! // private var _retailerIdentified = false private var _foundBeaconList = Dictionary<Int, (foundedCount: Int, proximity: Double)>() private var _dataInitialized = false { didSet{ Logger.sharedInstance.displayMessageInLabel(tableCellProgressMessage, msg: K.LoadingMessage.SEARCHING_BEACONS) initBeaconDiscover() } } private var _retailerUUID: String! { didSet { // _retailerIdentified = true print("Retailer identified") } } @IBOutlet var tableViewProgressView: UIView! @IBOutlet var tableCellProgressMessage: UILabel! @IBOutlet var tableCellProgressIndicator: UIActivityIndicatorView! @IBOutlet weak var itemTable: UITableView! override func viewDidLoad() { super.viewDidLoad() itemTable.registerNib(UINib(nibName: "ItemTableCell", bundle: nil), forCellReuseIdentifier: "itemTableCell") tableCellProgressIndicator.startAnimating() initApplicationData() itemTable.delegate = self itemTable.dataSource = self DataInitializer.sharedInstance.delegate = self } override func viewDidAppear(animated: Bool) { checkLogin() } func initApplicationData(){ // initBeaconList() DataInitializer.sharedInstance.initApplicationData() } // /** // Initialization of beacon list from server. Downloading only beacons with proximityUUID setted. // */ // func initBeaconList() { // // Logger.sharedInstance.displayMessageInLabel(tableCellProgressMessage, msg: K.LoadingMessage.LOADING_BEACONS) // // let props = [K.BackendAPI.Entity.BeaconEntity.Identifier.rawValue, K.BackendAPI.Entity.BeaconEntity.ProximityUUID.rawValue] // // HttpRequestService.sharedInstance.GetDataWithProps(K.BackendAPI.Entity.EntityURL.Beacons, props: props, downloadHandler: { // data in // print("ViewController:initBeaconList: Parsing received data...") // if data != nil { // if let dataList = data!["data"] as? [Dictionary<String, AnyObject>] { // for row in dataList { // if let id = row["identifier"] as? String, // let prox = row["proximityUUID"] as? String // { // BeaconData.sharedInstance.AddBeaconDataToList((id,prox)) // } // } // } // } // // 2. init BT beacon detector // self.initBluetoothDiscover() // }) // } // /** // Initialization of BeaconBluetoothDiscovery object and start detecting peripherals. // */ // func initBluetoothDiscover() { // // Logger.sharedInstance.displayMessageInLabel(tableCellProgressMessage, msg: K.LoadingMessage.DETECTING_BLE_PERIPHERALS) // // _bluetoothDetector = BeaconBluetoothDiscovery() // _bluetoothDetector.delegate = self // } /** Initialization of BeaconFinder object and start monitoring beacons with given uuid. */ func initBeaconDiscover() { _beaconDetector = BeaconFinder(uuid: _retailerUUID) _beaconDetector.delegate = self } // /** // * // */ // func initItems(){ // // let props = [K.BackendAPI.Entity.ItemEntity.Name.rawValue, // K.BackendAPI.Entity.ItemEntity.Favourite.rawValue, // K.BackendAPI.Entity.ItemEntity.CellDesc.rawValue, // K.BackendAPI.Entity.ItemEntity.Price.rawValue, // K.BackendAPI.Entity.ItemEntity.ObjectId.rawValue, // K.BackendAPI.Entity.ItemEntity.ThumbImageURL.rawValue // ] // // let relations = ["BeaconID"] // // // HttpRequestService.sharedInstance.GetDataWithRelations(K.BackendAPI.Entity.EntityURL.Items, props: props, relations: relations, downloadHandler: { // data in // // if data != nil { // if let dataList = data!["data"] as? [Dictionary<String, AnyObject>] { // for row in dataList { // // if let name = row[K.BackendAPI.Entity.ItemEntity.Name.rawValue] as? String, // let favo = row[K.BackendAPI.Entity.ItemEntity.Favourite.rawValue] as? Bool, // let desc = row[K.BackendAPI.Entity.ItemEntity.CellDesc.rawValue] as? String, // let price = row[K.BackendAPI.Entity.ItemEntity.Price.rawValue] as? Double, // let id = row[K.BackendAPI.Entity.ItemEntity.ObjectId.rawValue] as? String, // let img = row[K.BackendAPI.Entity.ItemEntity.ThumbImageURL.rawValue] as? String // { // // let item = Item(name: name, descr: desc, price: price, isFavourite: favo, objID: id, thumb: img) // let imgURL = NSURL(string: img) // // DataDownloader.DownloadDataFromUrl(imgURL!, downloadedHandler: { // (pathToDownloadedFile) in // // let loadablePath = FileManager.MakeLoadablePathFromURL(pathToDownloadedFile) // item.Image = UIImage(contentsOfFile: loadablePath)! // // }) // // if let beaconInfo = row["BeaconID"] as? Dictionary<String, AnyObject> { // if let identifier = beaconInfo["identifier"] as? String, // let proximity = beaconInfo["proximityUUID"] as? String, // let major = beaconInfo["major"] as? Int, // let minor = beaconInfo["minor"] as? Int { // // let beacon = Beacon(identifier: identifier, UUID: proximity, major: major, minor: minor) // item.BeaconObject = beacon // } // } // // BeaconData.sharedInstance.AddItem(item) // } // } // } // } // self._dataInitialized = true // }) // } func checkLogin() { if let user: String? = NSUserDefaults.standardUserDefaults().valueForKey(K.UserSession.SESSION_USERNAME_KEY) as? String { return } let loginStoryBrd: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) let viewController: UIViewController = loginStoryBrd.instantiateViewControllerWithIdentifier("LoginViewController") as UIViewController presentViewController(viewController, animated: true, completion: nil) } // ------------------------------------------------------------------------------------ // DataInitializer delegate methods implementation // ------------------------------------------------------------------------------------ func dataInitializerDelegate(didDataInitialized retailerUUID: String) { _retailerUUID = retailerUUID initBeaconDiscover() } // ------------------------------------------------------------------------------------ // BTPeripheralDiscovery delegate methods implementation // ------------------------------------------------------------------------------------ // func peripheralDidDiscovered(didDiscoveredPeripheral peripheral: CBPeripheral, advertisedData: [String : AnyObject], RSSI: NSNumber) { // print("ViewController:peripheralDidDiscovered: \(peripheral)...discovered\n\n") // // // // if let proximityId = BeaconData.sharedInstance.AvailableBeaconList[peripheral.identifier.UUIDString] { // print("ViewController: Retailer ID found") // _retailerUUID = proximityId // _bluetoothDetector.stopDiscoveringPeripherals() // // } // // // if _retailerIdentified { // // 3. Download items for retailer // Logger.sharedInstance.displayMessageInLabel(tableCellProgressMessage, msg: K.LoadingMessage.LOADING_ITEMS) // initItems() // // } // } // ------------------------------------------------------------------------------------ // BeaconDetectorDelegate methods implementation // ------------------------------------------------------------------------------------ func beaconDidFound(beacons: [Beacon], inRegion region: CLRegion) { print("\(beacons)") for b in beacons { let hashIndex = b.hash let prox = b.Beacon.accuracy print("\(prox)") let pairedBeacon: BeaconItemPair? = getPairedBeacon(b) var isInShowList: Bool = true if pairedBeacon == nil { continue } isInShowList = isShowedInList(pairedBeacon!) if prox <= K.Proximity.ALLOWED_PROXIMITY{ // insert item to showing list if !isInShowList { BeaconData.sharedInstance.AddShowingBeacon(pairedBeacon!) } }else { // remove item from showing list if isInShowList { BeaconData.sharedInstance.RemoveShowingBeacon(pairedBeacon!) } } itemTable.reloadData() } } func isShowedInList(entry: BeaconItemPair) -> Bool { let data = BeaconData.sharedInstance let index = data.getShowingItemsIndex(entry.item.BeaconObject.hash) return index == -1 ? false : true } func getPairedBeacon(b: Beacon) -> BeaconItemPair? { var pairedBeacon: BeaconItemPair? if (BeaconData.sharedInstance.Items[b.hash] != nil) { pairedBeacon = (BeaconData.sharedInstance.Items[b.hash]!, b) } return pairedBeacon } // ------------------------------------------------------------------------------------ // TableView delegate methods implementation // ------------------------------------------------------------------------------------ func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return BeaconData.sharedInstance.ShowingBeaconsHash.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let data = BeaconData.sharedInstance let cell = itemTable.dequeueReusableCellWithIdentifier("itemTableCell") as? itemTableCellView // let values = DictionaryHelper.DictionaryToArray(dictionaryToConvert: BeaconData.sharedInstance.ShowingBeaconsHash) let index = data.ShowingBeaconsHash[indexPath.row] cell?.configureMercCell(BeaconData.sharedInstance.Items[index.itemIndex]!) return cell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let data = BeaconData.sharedInstance let mainIndex = data.ShowingBeaconsHash[indexPath.row].itemIndex let item = data.Items[mainIndex] performSegueWithIdentifier("showItemDetail", sender: item) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let item = sender as? Item { if let destination = segue.destinationViewController as? ItemDetailViewController { destination.detailItem = item } } } }
apache-2.0
32a9128656150087e6baf8af78e5a0b3
38.47678
161
0.541683
5.428267
false
false
false
false
fsproru/ScoutReport
ScoutReportTests/Suspect.swift
1
435
@testable import ScoutReport extension Suspect { static func chooseStubbedSuspect(instagramUsername instagramUsername: String = "hulk", youtubeUsername: String = "big_nice_green_guy", instagramAccessToken: String? = nil) { let stubbedSuspect = Suspect(instagramUsername: instagramUsername, youtubeUsername: youtubeUsername, instagramAccessToken: instagramAccessToken) Suspect.chosenSuspect = stubbedSuspect } }
mit
b7dc0f0d25aa85867b37a3998cb5f1ff
53.5
177
0.786207
4.728261
false
true
false
false
MobileCoderMX/tutoriales
Aprendiendo iOS/GuardaInformacion/GuardaInformacion/ViewController.swift
1
2582
// // ViewController.swift // GuardaInformacion // // Created by Oscar Swanros on 4/19/15. // Copyright (c) 2015 MobileCoder. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { lazy var tableView: UITableView = { let tv = UITableView(frame: self.view.bounds, style: .Plain) tv.delegate = self tv.dataSource = self tv.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell") return tv }() var rightBarButtonItem: UIBarButtonItem { return UIBarButtonItem(title: "Agregar", style: .Plain, target: self, action: "rightBarButtonItemTapped") } // MARK: - Methods override func viewDidLoad() { super.viewDidLoad() self.title = "MobileCoder.mx" self.view.addSubview(self.tableView) self.navigationItem.rightBarButtonItem = self.rightBarButtonItem } func rightBarButtonItemTapped() { var alertController = UIAlertController(title: "Agregar", message: "Agregar banda", preferredStyle: .Alert) alertController.addTextFieldWithConfigurationHandler { textField in textField.placeholder = "Nombre de la banda" } alertController.addAction(UIAlertAction(title: "Cancelar", style: .Destructive, handler: nil)) alertController.addAction(UIAlertAction(title: "Agregar", style: .Default, handler: { alertAction in let textField = alertController.textFields?[0] as? UITextField dispatch_async(dispatch_get_main_queue(), { () -> Void in addBand(textField!.text) self.tableView.reloadData() }) })) self.presentViewController(alertController, animated: true, completion: nil) } // MARK: - TableView Datasource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return bands.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as? UITableViewCell cell?.textLabel?.text = bands[indexPath.row] return cell! } // MARK: - TableView Delegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
mit
79df2fd0063ad076976f904e303adfd0
32.973684
115
0.656468
5.269388
false
false
false
false
danielsaidi/iExtra
iExtraTests/UI/Extensions/UIView/UIView+RoundTests.swift
1
1572
// // UIView+RoundTests.swift // iExtra // // Created by Daniel Saidi on 2016-12-12. // Copyright © 2016 Daniel Saidi. All rights reserved. // import Quick import Nimble import iExtra class UIView_RoundTests: QuickSpec { override func spec() { describe("round view") { it("is rounded with small height value") { let frame = CGRect(x: 0, y: 0, width: 10, height: 100) let view = UIView(frame: frame) view.makeRoundWithHeightRadius() expect(view.layer.cornerRadius).to(equal(50)) } it("is rounded with small width value") { let frame = CGRect(x: 0, y: 0, width: 100, height: 10) let view = UIView(frame: frame) view.makeRoundWithWidthRadius() expect(view.layer.cornerRadius).to(equal(50)) } it("is rounded with large height value") { let frame = CGRect(x: 0, y: 0, width: 10, height: 10000) let view = UIView(frame: frame) view.makeRoundWithHeightRadius() expect(view.layer.cornerRadius).to(equal(5000)) } it("is rounded with large width value") { let frame = CGRect(x: 0, y: 0, width: 10000, height: 10) let view = UIView(frame: frame) view.makeRoundWithWidthRadius() expect(view.layer.cornerRadius).to(equal(5000)) } } } }
mit
14be639803aad861faeeca43c141423b
31.729167
72
0.516868
4.450425
false
false
false
false
taher-mosbah/firefox-ios
Client/Frontend/Widgets/ThumbnailCell.swift
1
10335
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared struct ThumbnailCellUX { /// Ratio of width:height of the thumbnail image. static let ImageAspectRatio: Float = 1.0 static let TextSize = UIConstants.DefaultSmallFontSize static let BorderColor = UIColor.blackColor().colorWithAlphaComponent(0.1) static let BorderWidth: CGFloat = 1 static let SelectedBackgroundColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.blackColor() : UIColor.lightGrayColor() static let LabelFont = UIConstants.DefaultSmallFont static let LabelColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.blackColor() : UIColor(rgb: 0x353535) static let LabelBackgroundColor = UIColor(white: 1.0, alpha: 0.5) static let LabelAlignment: NSTextAlignment = .Center static let InsetSize: CGFloat = 20 static let InsetSizeCompact: CGFloat = 6 static var Insets: UIEdgeInsets { let inset: CGFloat = (UIScreen.mainScreen().traitCollection.horizontalSizeClass == .Compact) ? ThumbnailCellUX.InsetSizeCompact : ThumbnailCellUX.InsetSize return UIEdgeInsetsMake(inset, inset, inset, inset) } static let ImagePadding: CGFloat = 20 static let ImagePaddingCompact: CGFloat = 10 static let LabelInsets = UIEdgeInsetsMake(10, 3, 10, 3) static let PlaceholderImage = UIImage(named: "defaultTopSiteIcon") static let CornerRadius: CGFloat = 3 // Make the remove button look 20x20 in size but have the clickable area be 44x44 static let RemoveButtonSize: CGFloat = 44 static let RemoveButtonInsets = UIEdgeInsets(top: 11, left: 11, bottom: 11, right: 11) static let RemoveButtonAnimationDuration: NSTimeInterval = 0.4 static let RemoveButtonAnimationDamping: CGFloat = 0.6 static let NearestNeighbordScalingThreshold: CGFloat = 24 } @objc protocol ThumbnailCellDelegate { func didRemoveThumbnail(thumbnailCell: ThumbnailCell) func didLongPressThumbnail(thumbnailCell: ThumbnailCell) } class ThumbnailCell: UICollectionViewCell { weak var delegate: ThumbnailCellDelegate? var imagePadding: CGFloat = 0 { didSet { imageView.snp_remakeConstraints({ make in let insets = UIEdgeInsetsMake(imagePadding, imagePadding, imagePadding, imagePadding) make.top.left.right.equalTo(self.imageWrapper).insets(insets) make.bottom.equalTo(textWrapper.snp_top).offset(-imagePadding) }) imageView.setNeedsUpdateConstraints() } } var image: UIImage? = nil { didSet { if let image = image { imageView.image = image imageView.contentMode = UIViewContentMode.ScaleAspectFit // Force nearest neighbor scaling for small favicons if image.size.width < ThumbnailCellUX.NearestNeighbordScalingThreshold { imageView.layer.shouldRasterize = true imageView.layer.rasterizationScale = 2 imageView.layer.minificationFilter = kCAFilterNearest imageView.layer.magnificationFilter = kCAFilterNearest } } else { imageView.image = ThumbnailCellUX.PlaceholderImage imageView.contentMode = UIViewContentMode.Center } } } lazy var longPressGesture: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: "SELdidLongPress") }() lazy var textWrapper: UIView = { let wrapper = UIView() wrapper.backgroundColor = ThumbnailCellUX.LabelBackgroundColor return wrapper }() lazy var textLabel: UILabel = { let textLabel = UILabel() textLabel.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Vertical) textLabel.font = ThumbnailCellUX.LabelFont textLabel.textColor = ThumbnailCellUX.LabelColor textLabel.textAlignment = ThumbnailCellUX.LabelAlignment return textLabel }() lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = UIViewContentMode.ScaleAspectFit imageView.clipsToBounds = true imageView.layer.cornerRadius = ThumbnailCellUX.CornerRadius return imageView }() lazy var backgroundImage: UIImageView = { let backgroundImage = UIImageView() backgroundImage.contentMode = UIViewContentMode.ScaleAspectFill return backgroundImage }() lazy var backgroundEffect: UIVisualEffectView = { let blur = UIBlurEffect(style: UIBlurEffectStyle.Light) let vib = UIVibrancyEffect(forBlurEffect: blur) return UIVisualEffectView(effect: blur) }() lazy var imageWrapper: UIView = { let imageWrapper = UIView() imageWrapper.layer.borderColor = ThumbnailCellUX.BorderColor.CGColor imageWrapper.layer.borderWidth = ThumbnailCellUX.BorderWidth imageWrapper.layer.cornerRadius = ThumbnailCellUX.CornerRadius imageWrapper.clipsToBounds = true return imageWrapper }() lazy var removeButton: UIButton = { let removeButton = UIButton() removeButton.setImage(UIImage(named: "TileCloseButton"), forState: UIControlState.Normal) removeButton.addTarget(self, action: "SELdidRemove", forControlEvents: UIControlEvents.TouchUpInside) removeButton.hidden = true removeButton.imageEdgeInsets = ThumbnailCellUX.RemoveButtonInsets return removeButton }() override init(frame: CGRect) { super.init(frame: frame) isAccessibilityElement = true addGestureRecognizer(longPressGesture) contentView.addSubview(imageWrapper) imageWrapper.addSubview(backgroundImage) imageWrapper.addSubview(backgroundEffect) imageWrapper.addSubview(imageView) imageWrapper.addSubview(textWrapper) textWrapper.addSubview(textLabel) contentView.addSubview(removeButton) imageWrapper.snp_remakeConstraints({ make in make.top.bottom.left.right.equalTo(self.contentView).insets(ThumbnailCellUX.Insets) }) backgroundImage.snp_remakeConstraints({ make in make.top.bottom.left.right.equalTo(self.imageWrapper) }) backgroundEffect.snp_remakeConstraints({ make in make.top.bottom.left.right.equalTo(self.imageWrapper) }) imageView.snp_remakeConstraints({ make in let imagePadding: CGFloat = (UIScreen.mainScreen().traitCollection.horizontalSizeClass == .Compact) ? ThumbnailCellUX.ImagePaddingCompact : ThumbnailCellUX.ImagePadding let insets = UIEdgeInsetsMake(imagePadding, imagePadding, imagePadding, imagePadding) make.top.left.right.equalTo(self.imageWrapper).insets(insets) make.bottom.equalTo(textWrapper.snp_top).offset(-imagePadding) // .insets(insets) }) textWrapper.snp_makeConstraints({ make in make.bottom.equalTo(self.imageWrapper.snp_bottom) // .offset(ThumbnailCellUX.BorderWidth) make.left.right.equalTo(self.imageWrapper) // .offset(ThumbnailCellUX.BorderWidth) }) textLabel.snp_remakeConstraints({ make in make.edges.equalTo(self.textWrapper).insets(ThumbnailCellUX.LabelInsets) return }) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() // TODO: We can avoid creating this button at all if we're not in editing mode. var frame = removeButton.frame let insets = ThumbnailCellUX.Insets frame.size = CGSize(width: ThumbnailCellUX.RemoveButtonSize, height: ThumbnailCellUX.RemoveButtonSize) frame.center = CGPoint(x: insets.left, y: insets.top) removeButton.frame = frame } func SELdidRemove() { delegate?.didRemoveThumbnail(self) } func SELdidLongPress() { delegate?.didLongPressThumbnail(self) } func toggleRemoveButton(show: Bool) { // Only toggle if we change state if removeButton.hidden != show { return } if show { removeButton.hidden = false } let scaleTransform = CGAffineTransformMakeScale(0.01, 0.01) removeButton.transform = show ? scaleTransform : CGAffineTransformIdentity UIView.animateWithDuration(ThumbnailCellUX.RemoveButtonAnimationDuration, delay: 0, usingSpringWithDamping: ThumbnailCellUX.RemoveButtonAnimationDamping, initialSpringVelocity: 0, options: UIViewAnimationOptions.AllowUserInteraction | UIViewAnimationOptions.CurveEaseInOut, animations: { self.removeButton.transform = show ? CGAffineTransformIdentity : scaleTransform }, completion: { _ in if !show { self.removeButton.hidden = true } }) } var imagePadding: CGFloat { didSet { imageView.snp_remakeConstraints({ make in make.top.bottom.left.right.equalTo(self.imageWrapper).insets(UIEdgeInsetsMake(imagePadding, imagePadding, imagePadding, imagePadding)) }) } } var image: UIImage? = nil { didSet { if let image = image { imageView.image = image imageView.alignment = UIImageViewAlignmentMaskTop imageView.contentMode = UIViewContentMode.ScaleAspectFill } else { imageView.image = ThumbnailCellUX.PlaceholderImage imageView.alignment = UIImageViewAlignmentMaskCenter imageView.contentMode = UIViewContentMode.Center } } } override var selected: Bool { willSet { super.selected = selected if (selected) { self.backgroundColor = ThumbnailCellUX.SelectedBackgroundColor } } } }
mpl-2.0
98db367a972e13d781c0741cc09aaab8
38.446565
180
0.672085
5.626021
false
false
false
false
Armanoide/VisualHumainNumber
SRC/VisualHumainNumber.swift
1
10479
// // File.swift // VisualHumainNumber // // Created by Norbert Billa on 04/09/2015. // Copyright (c) 2015 norbert-billa. All rights reserved. // import Foundation /// These constants specify predefined number format visual styles. /// These constants are used by the getVisualHumainNumbers func. /// /// Indentation will create a code block, handy for example usage: /// /// /// 1. **simpleHumain** /// (ex: 4532456) => 4M /// 2. **separatorHundred** /// (ex: 4532456.43) => 4,532,456.43 /// 3. **separatorHundredRounded** /// (ex: 4532456.43) => 4 532 456.43 /// /// /// - returns: VisualHumainNumberNotation. @objc public enum VisualHumainNumberNotation : Int { case simpleHumain case separatorHundred case separatorHundredRounded } @objc public class VisualHumainNumber: NSObject { fileprivate var visualHumainNumbersDecimal : Double = 0 fileprivate var visualHumainNumbersInteger : Int64 = 0 fileprivate var _separator: String = "," fileprivate (set) var isNegative : Bool = false var separator: String? { get { return _separator } set { if let newValue = newValue { self._separator = newValue; } } } public init(string :String, separator: String? = nil) { super.init () self.separator = separator; _ = self.setNumber(string: string) } public init(double: Double, separator: String? = nil) { super.init () self.separator = separator; _ = self.setNumber(double: double) } public init(long: Int64, separator: String? = nil) { super.init () self.separator = separator; _ = self.setNumber(long: long) } open func setNumber(string : String) -> VisualHumainNumber { self.visualHumainNumbersDecimal = VisualHumainNumber.trimAllNumberToDecimal(string) self.visualHumainNumbersInteger = VisualHumainNumber.trimAllNumberToInt(string) checkIfIsNegative() return self } open func setNumber(double: Double) -> VisualHumainNumber { self.visualHumainNumbersDecimal = double self.visualHumainNumbersInteger = Int64(floor(double)) checkIfIsNegative() return self } open func setNumber(long: Int64) -> VisualHumainNumber { self.visualHumainNumbersDecimal = Double(long) self.visualHumainNumbersInteger = long checkIfIsNegative() return self } fileprivate func checkIfIsNegative() { if self.visualHumainNumbersDecimal < 0 || self.visualHumainNumbersInteger < 0 { self.isNegative = true } } fileprivate func appendSeparator(notation : VisualHumainNumberNotation, lenghtForSeparator : Int, separator : String) -> String { var s = "" var result = "" var __all_count = 0 // for resverse wait to start after coma like 04.432, start apply stuff after 04. var __start = true; var __true_length_decimal = 0; if notation == .separatorHundredRounded { __start = false; __true_length_decimal = 3; } /*var __start = (notation == .separatorHundredRounded) ? false : true let __true_length_decimal = (notation == .separatorHundredRounded) ? 3 : 0*/ switch notation { case .separatorHundredRounded : s = VisualHumainNumber.inverseString(String(stringInterpolationSegment: self.visualHumainNumbersDecimal)) break default: s = VisualHumainNumber.inverseString(String(stringInterpolationSegment: self.visualHumainNumbersInteger)) break } if self.isNegative { let endIndex = s.index(s.endIndex, offsetBy: -1) let lastCharacter = s.substring(from: endIndex) if lastCharacter == "-" { s = s.substring(to: endIndex) } } for c in s.characters { if __start == true { if __all_count % lenghtForSeparator == 0 && __all_count <= s.characters.count - __true_length_decimal && __all_count > 0 { result.append(separator) } __all_count += 1 } else if c == "." { __start = true } result.append(c) } if self.isNegative { result.append("-") } return VisualHumainNumber.inverseString(result) } fileprivate func simpleHumain(notation : VisualHumainNumberNotation) -> String { var __ = self.visualHumainNumbersDecimal var r : Double = 0 var finalNotation : VisualHumainNumberNotation = .separatorHundredRounded var type = 0 // check if is negative if self.isNegative { __ = __ * -1 } if __ < 1000 { r = __ } else if __ < 1000000 { r = __ / 1000 type = 1 } else if __ < 1000000000{ r = __ / 1000000 type = 2 } else { r = __ / 1000000000 type = 3 } var rs = "\(floor(r * 10) / 10)" if (floor(r * 10) / 10).truncatingRemainder(dividingBy: 1) == 0 { rs = "\(Int64(floor(r)))" ; finalNotation = .separatorHundred } let __rs_i = VisualHumainNumber.getDoubleFromString(rs) ; if __rs_i >= 100 { rs = "\(Int64(floor(__rs_i)))" ; finalNotation = .separatorHundred } let __arr = VisualHumainNumber(string: rs) var result = __arr.getVisualHumainNumbers(notation: finalNotation) + (type == 1 ? "k" : (type == 2 ? "M" : (type == 3 ? "B" : ""))) if isNegative { result = "-" + result } return result } /// Function getVisualHumainNumbers transform big number into a visual number for humain /// /// /// /// - parameter VisualHumainNumberNotation: use to determine the fomat to display number. /// - returns: String. open func getVisualHumainNumbers(notation : VisualHumainNumberNotation) -> String { if self.visualHumainNumbersDecimal == 0 { return "0" } switch notation { case .simpleHumain: return self.simpleHumain(notation: notation) case .separatorHundred, .separatorHundredRounded: return self.appendSeparator(notation: notation, lenghtForSeparator: 3, separator: self.separator!) } } /// Function inverse order of a string, the 1 become last and last the first. /// /// /// /// - parameter String: The string to reverse order. /// - returns: String. open class func inverseString (_ string :String) -> String { var s = "" for c in string.characters { s = "\(c)" + s } return s } /// Determine if the Character is a number. /// /// /// /// - parameter Character: /// - returns: Bool. open class func isCharacterNumber(_ c: Character) -> Bool { switch String(c) { case "0", "1", "2", "3", "4", "5", "6", "6", "7", "8", "9" : return true default: return false } } /// Determine if the Character is a marker of decimal. /// /// /// /// - parameter Character: /// - returns: Bool. open class func isCharacterMarkerDecimal(_ c : Character) -> Bool { switch String(c) { case ",", "." : return true default: return false } } fileprivate class func getCh(_ c : Character) -> Int { switch c { case "0": return 0 case "1": return 1 case "2": return 2 case "3": return 3 case "4": return 4 case "5": return 5 case "6": return 6 case "7": return 7 case "8": return 8 case "9": return 9 default: return 0 } } fileprivate class func getDoubleFromString(_ numberString: String) -> Double { var number : Double = 0 var mul : Double = 1 var __P = "UP" for c in numberString.characters { if VisualHumainNumber.isCharacterMarkerDecimal(c) { __P = "DOWN" mul = 0.1 } else { if __P == "UP" { number = number * 10 + Double(VisualHumainNumber.getCh(c)) } else { number = number + Double(VisualHumainNumber.getCh(c)) * mul mul /= 10 } } } return number } fileprivate class func getIntegerFromString(_ numberString: String) -> Int64 { var number : Int64 = 0 for c in numberString.characters { if VisualHumainNumber.isCharacterMarkerDecimal(c) { break } number = number * 10 + Int64(VisualHumainNumber.getCh(c)) } return number } /// Function collect all number found in the string and cast to double /// /// /// /// - parameter String: /// - returns: Bool. open class func trimAllNumberToDecimal(_ string : String) -> Double { var numberString : String = "" var isNegative = false for c in string.characters { if VisualHumainNumber.isCharacterNumber(c) == true { numberString.append(c) } else if VisualHumainNumber.isCharacterMarkerDecimal(c) == true { numberString.append(Character(",")) } else if c == "-" && numberString.isEmpty { isNegative = !isNegative } } if isNegative { return self.getDoubleFromString(numberString) * -1 } else { return self.getDoubleFromString(numberString) } } /// Function collect all number found in the string and cast to interger /// /// /// /// - parameter String: /// - returns: Bool. open class func trimAllNumberToInt(_ string : String) -> Int64 { var numberString : String = "" for c in string.characters { if VisualHumainNumber.isCharacterNumber(c) == true { numberString.append(c) } else if VisualHumainNumber.isCharacterMarkerDecimal(c) == true { numberString.append(Character(".")) } } return getIntegerFromString(numberString) } }
mit
f672a7f7ed82d8bcc884c6e510f4b136
28.189415
154
0.558259
4.705433
false
false
false
false
nikHowlett/Attend-O
attendo1/Announcement.swift
1
4290
// // Announcement.swift // T-Squared for Georgia Tech // // Created by Cal on 8/28/15. // Copyright © 2015 Cal Stephens. All rights reserved. // import Foundation import Kanna let TSReadAnnouncementsKey = "edu.gatech.cal.readAnnouncements" class Announcement : CustomStringConvertible { let owningClass: Class let name: String var message: String? var author: String var date: NSDate? var rawDateString: String let link: String var attachments: [Attachment]? var description: String { return name } init(inClass: Class, name: String, author: String, date: String, link: String) { self.owningClass = inClass self.name = name self.author = author self.link = link self.rawDateString = date self.date = date.dateWithTSquareFormat() } func loadMessage(completion: (String) -> ()) { //only load if necessary if let message = self.message { completion(message) return } //load message dispatch_async(TSNetworkQueue, { if let page = HttpClient.contentsOfPage(self.link) { if !page.toHTML!.containsString("<p>") { self.loadMessage(completion) } else { var message: String = "" for pTag in page.css("p") { message += pTag.textWithLineBreaks for div in pTag.css("div") { message += div.textWithLineBreaks } } for imgTag in page.css("img") { if let src = imgTag["src"] where src.containsString("http") { let attachment = Attachment(link: src, fileName: "Attached image") if self.attachments == nil { self.attachments = [] } self.attachments!.append(attachment) } } self.message = message.withNoTrailingWhitespace() //load attachments if present for link in page.css("a, link") { let linkURL = link["href"] ?? "" if linkURL.containsString("/attachment/") { let attachment = Attachment(link: linkURL, fileName: link.text?.cleansed() ?? "Attached file") if self.attachments == nil { self.attachments = [] } self.attachments!.append(attachment) } } sync() { completion(self.message!) } } } else { sync() { completion("Couldn't load message.") } } }) } func hasBeenRead() -> Bool { guard let date = self.date else { return true } let data = NSUserDefaults.standardUserDefaults() //mark as read if the announcement pre-dates the install date of the app if let installDate = data.valueForKey(TSInstallDateKey) as? NSDate { if installDate.timeIntervalSinceDate(date) > 0 { return true } } let read = data.valueForKey(TSReadAnnouncementsKey) as? [NSDate] ?? [] return read.contains(date) } func markRead() { guard let date = self.date else { return } let data = NSUserDefaults.standardUserDefaults() var read = data.valueForKey(TSReadAnnouncementsKey) as? [NSDate] ?? [] read.insert(date, atIndex: 0) data.setValue(read, forKey: TSReadAnnouncementsKey) } } class Attachment { let link: String? let fileName: String let rawText: String? init(link: String, fileName: String) { self.link = link self.fileName = fileName self.rawText = nil } init(fileName: String, rawText: String) { self.link = nil self.rawText = rawText self.fileName = fileName } }
mit
f33cc1000f542d8bdde089e77dcc22ae
30.777778
122
0.503381
5.105952
false
false
false
false
lorentey/swift
test/decl/func/operator.swift
3
16929
// RUN: %target-typecheck-verify-swift infix operator %%% infix operator %%%% func %%%() {} // expected-error {{operators must have one or two arguments}} func %%%%(a: Int, b: Int, c: Int) {} // expected-error {{operators must have one or two arguments}} struct X {} struct Y {} func +(lhs: X, rhs: X) -> X {} // okay func <=>(lhs: X, rhs: X) -> X {} // expected-error {{operator implementation without matching operator declaration}}{{1-1=infix operator <=> : <# Precedence Group #>\n}} extension X { static func <=>(lhs: X, rhs: X) -> X {} // expected-error {{operator implementation without matching operator declaration}}{{1-1=infix operator <=> : <# Precedence Group #>\n}} } extension X { struct Z { static func <=> (lhs: Z, rhs: Z) -> Z {} // expected-error {{operator implementation without matching operator declaration}}{{1-1=infix operator <=> : <# Precedence Group #>\n}} } } extension X { static prefix func <=>(lhs: X) -> X {} // expected-error {{operator implementation without matching operator declaration}}{{1-1=prefix operator <=> : <# Precedence Group #>\n}} } extension X { struct ZZ { static prefix func <=>(lhs: ZZ) -> ZZ {} // expected-error {{operator implementation without matching operator declaration}}{{1-1=prefix operator <=> : <# Precedence Group #>\n}} } } infix operator ++++ : ReallyHighPrecedence precedencegroup ReallyHighPrecedence { higherThan: BitwiseShiftPrecedence associativity: left } infix func fn_binary(_ lhs: Int, rhs: Int) {} // expected-error {{'infix' modifier is not required or allowed on func declarations}} func ++++(lhs: X, rhs: X) -> X {} func ++++(lhs: Y, rhs: Y) -> Y {} // okay func useInt(_ x: Int) {} func test() { var x : Int let y : Int = 42 // Produce a diagnostic for using the result of an assignment as a value. // rdar://12961094 useInt(x = y) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}} _ = x } prefix operator ~~ postfix operator ~~ infix operator ~~ postfix func foo(_ x: Int) {} // expected-error {{'postfix' requires a function with an operator identifier}} postfix func ~~(x: Int) -> Float { return Float(x) } postfix func ~~(x: Int, y: Int) {} // expected-error {{'postfix' requires a function with one argument}} prefix func ~~(x: Float) {} func test_postfix(_ x: Int) { ~~x~~ } prefix operator ~~~ // expected-note 2{{prefix operator found here}} // Unary operators require a prefix or postfix attribute func ~~~(x: Float) {} // expected-error{{prefix unary operator missing 'prefix' modifier}}{{1-1=prefix }} protocol P { static func ~~~(x: Self) // expected-error{{prefix unary operator missing 'prefix' modifier}}{{10-10=prefix }} } prefix func +// this should be a comment, not an operator (arg: Int) -> Int { return arg } prefix func -/* this also should be a comment, not an operator */ (arg: Int) -> Int { return arg } func +*/ () {} // expected-error {{expected identifier in function declaration}} expected-error {{unexpected end of block comment}} expected-error {{closure expression is unused}} expected-error{{top-level statement cannot begin with a closure expression}} expected-note{{did you mean to use a 'do' statement?}} {{13-13=do }} func errors() { */ // expected-error {{unexpected end of block comment}} // rdar://12962712 - reject */ in an operator as it should end a block comment. */+ // expected-error {{unexpected end of block comment}} } prefix operator ... prefix func ... (arg: Int) -> Int { return arg } func resyncParser() {} // Operator decl refs (<op>) infix operator +-+ prefix operator +-+ prefix operator -+- postfix operator -+- infix operator +-+= infix func +-+ (x: Int, y: Int) -> Int {} // expected-error {{'infix' modifier is not required or allowed on func declarations}} {{1-7=}} prefix func +-+ (x: Int) -> Int {} prefix func -+- (y: inout Int) -> Int {} // expected-note 2{{found this candidate}} postfix func -+- (x: inout Int) -> Int {} // expected-note 2{{found this candidate}} infix func +-+= (x: inout Int, y: Int) -> Int {} // expected-error {{'infix' modifier is not required or allowed on func declarations}} {{1-7=}} var n = 0 // Infix by context _ = (+-+)(1, 2) // Prefix by context _ = (+-+)(1) // Ambiguous -- could be prefix or postfix (-+-)(&n) // expected-error{{ambiguous use of operator '-+-'}} // Assignment operator refs become inout functions _ = (+-+=)(&n, 12) (+-+=)(n, 12) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{8-8=&}} var f1 : (Int, Int) -> Int = (+-+) var f2 : (Int) -> Int = (+-+) var f3 : (inout Int) -> Int = (-+-) // expected-error{{ambiguous use of operator '-+-'}} var f4 : (inout Int, Int) -> Int = (+-+=) var r5 : (a : (Int, Int) -> Int, b : (Int, Int) -> Int) = (+, -) var r6 : (a : (Int, Int) -> Int, b : (Int, Int) -> Int) = (b : +, a : -) struct f6_S { subscript(op : (Int, Int) -> Int) -> Int { return 42 } } var f6_s : f6_S var junk = f6_s[+] // Unicode operator names infix operator ☃ infix operator ☃⃠ // Operators can contain (but not start with) combining characters func ☃(x: Int, y: Int) -> Bool { return x == y } func ☃⃠(x: Int, y: Int) -> Bool { return x != y } var x, y : Int _ = x☃y _ = x☃⃠y // rdar://14705150 - crash on invalid func test_14705150() { let a = 4 var b! = a // expected-error {{type annotation missing in pattern}} // expected-error @-1 {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // expected-error @-2 {{expected expression}} } postfix operator ++ prefix operator ++ prefix postfix func ++(x: Int) {} // expected-error {{'postfix' contradicts previous modifier 'prefix'}} {{8-16=}} postfix prefix func ++(x: Float) {} // expected-error {{'prefix' contradicts previous modifier 'postfix'}} {{9-16=}} postfix prefix infix func ++(x: Double) {} // expected-error {{'prefix' contradicts previous modifier 'postfix'}} {{9-16=}} expected-error {{'infix' contradicts previous modifier 'postfix'}} {{16-22=}} infix prefix func +-+(x: Double, y: Double) {} // expected-error {{'infix' modifier is not required or allowed on func declarations}} {{1-7=}} expected-error{{'prefix' contradicts previous modifier 'infix'}} {{7-14=}} // Don't allow one to define a postfix '!'; it's built into the // language. Also illegal to have any postfix operator starting with '!'. postfix operator ! // expected-error {{cannot declare a custom postfix '!' operator}} expected-error {{expected operator name in operator declaration}} prefix operator & // expected-error {{cannot declare a custom prefix '&' operator}} // <rdar://problem/14607026> Restrict use of '<' and '>' as prefix/postfix operator names postfix operator > // expected-error {{cannot declare a custom postfix '>' operator}} prefix operator < // expected-error {{cannot declare a custom prefix '<' operator}} postfix func !(x: Int) { } // expected-error{{cannot declare a custom postfix '!' operator}} postfix func!(x: Int8) { } // expected-error{{cannot declare a custom postfix '!' operator}} prefix func & (x: Int) {} // expected-error {{cannot declare a custom prefix '&' operator}} // Only allow operators at global scope: func operator_in_func_bad () { prefix func + (input: String) -> String { return "+" + input } // expected-error {{operator functions can only be declared at global or in type scope}} } infix operator ? // expected-error {{expected operator name in operator declaration}} infix operator ??= func ??= <T>(result : inout T?, rhs : Int) { // ok } // <rdar://problem/14296004> [QoI] Poor diagnostic/recovery when two operators (e.g., == and -) are adjacted without spaces. _ = n*-4 // expected-error {{missing whitespace between '*' and '-' operators}} {{6-6= }} {{7-7= }} if n==-1 {} // expected-error {{missing whitespace between '==' and '-' operators}} {{5-5= }} {{7-7= }} prefix operator ☃⃠ prefix func☃⃠(a : Int) -> Int { return a } postfix operator ☃⃠ postfix func☃⃠(a : Int) -> Int { return a } _ = n☃⃠ ☃⃠ n // Ok. _ = n ☃⃠ ☃⃠n // Ok. _ = n ☃⃠☃⃠ n // expected-error {{use of unresolved operator '☃⃠☃⃠'}} _ = n☃⃠☃⃠n // expected-error {{ambiguous missing whitespace between unary and binary operators}} // expected-note @-1 {{could be binary '☃⃠' and prefix '☃⃠'}} {{12-12= }} {{18-18= }} // expected-note @-2 {{could be postfix '☃⃠' and binary '☃⃠'}} {{6-6= }} {{12-12= }} _ = n☃⃠☃⃠ // expected-error {{unary operators must not be juxtaposed; parenthesize inner expression}} _ = ~!n // expected-error {{unary operators must not be juxtaposed; parenthesize inner expression}} _ = -+n // expected-error {{unary operators must not be juxtaposed; parenthesize inner expression}} _ = -++n // expected-error {{unary operators must not be juxtaposed; parenthesize inner expression}} // <rdar://problem/16230507> Cannot use a negative constant as the second operator of ... operator _ = 3...-5 // expected-error {{ambiguous missing whitespace between unary and binary operators}} expected-note {{could be postfix '...' and binary '-'}} expected-note {{could be binary '...' and prefix '-'}} protocol P0 { static func %%%(lhs: Self, rhs: Self) -> Self } protocol P1 { func %%%(lhs: Self, rhs: Self) -> Self // expected-error{{operator '%%%' declared in protocol must be 'static'}}{{3-3=static }} } struct S0 { static func %%%(lhs: S0, rhs: S0) -> S0 { return lhs } } extension S0 { static func %%%%(lhs: S0, rhs: S0) -> S0 { return lhs } } struct S1 { func %%%(lhs: S1, rhs: S1) -> S1 { return lhs } // expected-error{{operator '%%%' declared in type 'S1' must be 'static'}}{{3-3=static }} } extension S1 { func %%%%(lhs: S1, rhs: S1) -> S1 { return lhs } // expected-error{{operator '%%%%' declared in extension of 'S1' must be 'static'}}{{3-3=static }} } class C0 { static func %%%(lhs: C0, rhs: C0) -> C0 { return lhs } } class C1 { final func %%%(lhs: C1, rhs: C1) -> C1 { return lhs } // expected-error{{operator '%%%' declared in type 'C1' must be 'static'}}{{3-3=static }} } final class C2 { class func %%%(lhs: C2, rhs: C2) -> C2 { return lhs } } class C3 { class func %%%(lhs: C3, rhs: C3) -> C3 { return lhs } // expected-error{{operator '%%%' declared in non-final class 'C3' must be 'final'}}{{3-3=final }} } class C4 { func %%%(lhs: C4, rhs: C4) -> C4 { return lhs } // expected-error{{operator '%%%' declared in type 'C4' must be 'static'}}{{3-3=static }} } struct Unrelated { } struct S2 { static func %%%(lhs: Unrelated, rhs: Unrelated) -> Unrelated { } // expected-error@-1{{member operator '%%%' must have at least one argument of type 'S2'}} static func %%%(lhs: Unrelated, rhs: Unrelated) -> S2 { } // expected-error@-1{{member operator '%%%' must have at least one argument of type 'S2'}} static func %%%(lhs: Unrelated, rhs: Unrelated) -> S2.Type { } // expected-error@-1{{member operator '%%%' must have at least one argument of type 'S2'}} // Okay: refers to S2 static func %%%(lhs: S2, rhs: Unrelated) -> Unrelated { } static func %%%(lhs: inout S2, rhs: Unrelated) -> Unrelated { } static func %%%(lhs: S2.Type, rhs: Unrelated) -> Unrelated { } static func %%%(lhs: inout S2.Type, rhs: Unrelated) -> Unrelated { } static func %%%(lhs: Unrelated, rhs: S2) -> Unrelated { } static func %%%(lhs: Unrelated, rhs: inout S2) -> Unrelated { } static func %%%(lhs: Unrelated, rhs: S2.Type) -> Unrelated { } static func %%%(lhs: Unrelated, rhs: inout S2.Type) -> Unrelated { } } extension S2 { static func %%%%(lhs: Unrelated, rhs: Unrelated) -> Unrelated { } // expected-error@-1{{member operator '%%%%' must have at least one argument of type 'S2'}} static func %%%%(lhs: Unrelated, rhs: Unrelated) -> S2 { } // expected-error@-1{{member operator '%%%%' must have at least one argument of type 'S2'}} static func %%%%(lhs: Unrelated, rhs: Unrelated) -> S2.Type { } // expected-error@-1{{member operator '%%%%' must have at least one argument of type 'S2'}} // Okay: refers to S2 static func %%%%(lhs: S2, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: inout S2, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: S2.Type, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: inout S2.Type, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: S2) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: inout S2) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: S2.Type) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: inout S2.Type) -> Unrelated { } } protocol P2 { static func %%%(lhs: Unrelated, rhs: Unrelated) -> Unrelated // expected-error@-1{{member operator '%%%' of protocol 'P2' must have at least one argument of type 'Self'}} static func %%%(lhs: Unrelated, rhs: Unrelated) -> Self // expected-error@-1{{member operator '%%%' of protocol 'P2' must have at least one argument of type 'Self'}} static func %%%(lhs: Unrelated, rhs: Unrelated) -> Self.Type // expected-error@-1{{member operator '%%%' of protocol 'P2' must have at least one argument of type 'Self'}} // Okay: refers to Self static func %%%(lhs: Self, rhs: Unrelated) -> Unrelated static func %%%(lhs: inout Self, rhs: Unrelated) -> Unrelated static func %%%(lhs: Self.Type, rhs: Unrelated) -> Unrelated static func %%%(lhs: inout Self.Type, rhs: Unrelated) -> Unrelated static func %%%(lhs: Unrelated, rhs: Self) -> Unrelated static func %%%(lhs: Unrelated, rhs: inout Self) -> Unrelated static func %%%(lhs: Unrelated, rhs: Self.Type) -> Unrelated static func %%%(lhs: Unrelated, rhs: inout Self.Type) -> Unrelated } extension P2 { static func %%%%(lhs: Unrelated, rhs: Unrelated) -> Unrelated { } // expected-error@-1{{member operator '%%%%' of protocol 'P2' must have at least one argument of type 'Self'}} static func %%%%(lhs: Unrelated, rhs: Unrelated) -> Self { } // expected-error@-1{{member operator '%%%%' of protocol 'P2' must have at least one argument of type 'Self'}} static func %%%%(lhs: Unrelated, rhs: Unrelated) -> Self.Type { } // expected-error@-1{{member operator '%%%%' of protocol 'P2' must have at least one argument of type 'Self'}} // Okay: refers to Self static func %%%%(lhs: Self, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: inout Self, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: Self.Type, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: inout Self.Type, rhs: Unrelated) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: Self) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: inout Self) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: Self.Type) -> Unrelated { } static func %%%%(lhs: Unrelated, rhs: inout Self.Type) -> Unrelated { } } protocol P3 { // Okay: refers to P3 static func %%%(lhs: P3, rhs: Unrelated) -> Unrelated } extension P3 { // Okay: refers to P3 static func %%%%(lhs: P3, rhs: Unrelated) -> Unrelated { } } // rdar://problem/27940842 - recovery with a non-static '=='. class C5 { func == (lhs: C5, rhs: C5) -> Bool { return false } // expected-error{{operator '==' declared in type 'C5' must be 'static'}} func test1(x: C5) { _ = x == x } } class C6 { static func == (lhs: C6, rhs: C6) -> Bool { return false } func test1(x: C6) { if x == x && x = x { } // expected-error{{use of '=' in a boolean context, did you mean '=='?}} {{20-21===}} // expected-error@-1 {{cannot convert value of type 'C6' to expected argument type 'Bool'}} } } prefix operator ∫ prefix func ∫(arg: (Int, Int)) {} func testPrefixOperatorOnTuple() { let foo = (1, 2) _ = ∫foo _ = (∫)foo // expected-error@-1 {{consecutive statements on a line must be separated by ';'}} // expected-warning@-2 {{expression of type '(Int, Int)' is unused}} _ = (∫)(foo) _ = ∫(1, 2) _ = (∫)(1, 2) // expected-error {{operator function '∫' expects a single parameter of type '(Int, Int)'}} _ = (∫)((1, 2)) } postfix operator § postfix func §<T, U>(arg: (T, (U, U), T)) {} // expected-note {{in call to operator '§'}} func testPostfixOperatorOnTuple<A, B>(a: A, b: B) { let foo = (a, (b, b), a) _ = foo§ // FIX-ME: "...could not be inferred" is irrelevant _ = (§)foo // expected-error@-1 {{consecutive statements on a line must be separated by ';'}} // expected-error@-2 {{generic parameter 'T' could not be inferred}} // expected-error@-3 {{generic parameter 'U' could not be inferred}} // expected-warning@-4 {{expression of type '(A, (B, B), A)' is unused}} _ = (§)(foo) _ = (a, (b, b), a)§ _ = (§)(a, (b, b), a) // expected-error {{operator function '§' expects a single parameter of type '(T, (U, U), T)'}} _ = (§)((a, (b, b), a)) _ = (a, ((), (b, (a, a), b)§), a)§ }
apache-2.0
7989fb8a68c9228d5c670fd9929cb91e
39.002381
327
0.627939
3.529622
false
false
false
false
smartmobilefactory/FolioReaderKit
Source/EPUBCore/FRTocReference.swift
2
908
// // FRTocReference.swift // FolioReaderKit // // Created by Heberti Almeida on 06/05/15. // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit class FRTocReference: NSObject { var resource: FRResource? var title: String! var fragmentID: String? var children: [FRTocReference]! convenience init(title: String, resource: FRResource?, fragmentID: String = "") { self.init(title: title, resource: resource, fragmentID: fragmentID, children: [FRTocReference]()) } init(title: String, resource: FRResource?, fragmentID: String, children: [FRTocReference]) { self.resource = resource self.title = title self.fragmentID = fragmentID self.children = children } } // MARK: Equatable func ==(lhs: FRTocReference, rhs: FRTocReference) -> Bool { return lhs.title == rhs.title && lhs.fragmentID == rhs.fragmentID }
bsd-3-clause
7c1fd811f2d5b5cf12bd8d08c26c5297
26.515152
105
0.672907
4.283019
false
false
false
false
krzysztofzablocki/Sourcery
SourceryFramework/Sources/Parsing/Utils/Verifier.swift
1
1170
// // Created by Krzysztof Zablocki on 23/01/2017. // Copyright (c) 2017 Pixle. All rights reserved. // import Foundation import PathKit import SourceryUtils public enum Verifier { // swiftlint:disable:next force_try private static let conflictRegex = try! NSRegularExpression(pattern: "^\\s+?(<<<<<|>>>>>)") public enum Result { case isCodeGenerated case containsConflictMarkers case approved } public static func canParse(content: String, path: Path, generationMarker: String, forceParse: [String] = []) -> Result { guard !content.isEmpty else { return .approved } let shouldForceParse = forceParse.contains { name in return path.hasExtension(as: name) } if content.hasPrefix(generationMarker) && shouldForceParse == false { return .isCodeGenerated } if conflictRegex.numberOfMatches(in: content, options: .anchored, range: content.bridge().entireRange) > 0 { return .containsConflictMarkers } return .approved } }
mit
6dcebb4935da3aff432dfea7da23b9e0
27.536585
116
0.597436
4.875
false
false
false
false
jshultz/ios9-swift2-playground
Contents.swift
1
1703
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" var name = "Yu Yu Hakashu" var nameDefined:String = "Type of var nameDefined Defined" print("Hello") print("Hello " + name + ".") var int:Int = 99 int += int //: it's like ruby. int = int * 2 int = int / 2 print("the value of int is \(int).") var number:Double = 8.4 var isMale = true var a:Double = 5.76 var b:Int = 8 print("The product of \(a) and \(b) equals \(a * Double(b))") //: Arrays var anArray:Array = [17,22,35,46] print(anArray[1]) //: Get's the second item in the array print(anArray.first) print(anArray.last) print(anArray.count) anArray.append(56) //: Add to the end of an array. anArray.popLast() //: remove the last anArray.removeAtIndex(2) //: remove the 3rd item from the array. anArray.sort() //: Sort that business. anArray //: This is what's left. var newArray = [50, 70, 90] newArray.removeAtIndex(1) newArray.append(newArray[0] + newArray[1]) //: Dictionaries var newDictionary = ["computer": "play call of duty on it", "red bull": "It's made of magic"] newDictionary.first print(newDictionary["red bull"]) //: shows Optional because 'red bull' may or may not exist' print(newDictionary["red bull"]!) //: forces it, i know that there is a value called 'red bull' in this dictionary. print(newDictionary.count) newDictionary["pen"] = "something you write with" newDictionary.removeValueForKey("pen") print(newDictionary) var priceList:Dictionary = ["red bull": 2.99, "mountain dew": 1.99, "hot dog": 1.00] var total = priceList["red bull"]! + priceList["mountain dew"]! + priceList["hot dog"]! print("total cost of the items is \(total)!")
mit
6ba457a77201317660f36c9b3eb7257d
19.035294
115
0.682325
3.219282
false
false
false
false
Zewo/HTTPSServer
Source/Server.swift
1
6420
// Server.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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. @_exported import TCPSSL @_exported import HTTPParser @_exported import HTTPSerializer public struct Server { public let server: C7.Host public let parser: S4.RequestParser public let middleware: [S4.Middleware] public let responder: S4.Responder public let serializer: S4.ResponseSerializer public let port: Int public let bufferSize: Int = 2048 public init(host: String = "0.0.0.0", port: Int = 8080, certificate: String, privateKey: String, certificateChain: String? = nil, reusePort: Bool = false, parser: S4.RequestParser = RequestParser(), middleware: Middleware..., responder: S4.Responder, serializer: S4.ResponseSerializer = ResponseSerializer()) throws { self.server = try TCPSSLServer( host: host, port: port, reusePort: reusePort, certificate: certificate, privateKey: privateKey, certificateChain: certificateChain ) self.parser = parser self.middleware = middleware self.responder = responder self.serializer = serializer self.port = port } public init(host: String = "0.0.0.0", port: Int = 8080, certificate: String, privateKey: String, certificateChain: String? = nil, reusingPort reusePort: Bool = false, parser: S4.RequestParser = RequestParser(), middleware: Middleware..., serializer: S4.ResponseSerializer = ResponseSerializer(), _ respond: Respond) throws { self.server = try TCPSSLServer( host: host, port: port, reusePort: reusePort, certificate: certificate, privateKey: privateKey, certificateChain: certificateChain ) self.parser = parser self.middleware = middleware self.responder = BasicResponder(respond) self.serializer = serializer self.port = port } } extension Server { public func start(_ failure: (ErrorProtocol) -> Void = Server.printError) throws { printHeader() while true { let stream = try server.accept(timingOut: .never) co { do { try self.processStream(stream) } catch { failure(error) } } } } private func processStream(_ stream: Stream) throws { while !stream.closed { do { let data = try stream.receive(upTo: bufferSize) try processData(data, stream: stream) } catch { let response = Response(status: .internalServerError) try serializer.serialize(response, to: stream) throw error } } } private func processData(_ data: Data, stream: Stream) throws { if let request = try parser.parse(data) { let response = try middleware.chain(to: responder).respond(to: request) try serializer.serialize(response, to: stream) if let upgrade = response.didUpgrade { try upgrade(request, stream) try stream.close() } if !request.isKeepAlive { try stream.close() } } } public func startInBackground(_ failure: (ErrorProtocol) -> Void = Server.printError) { co { do { try self.start() } catch { failure(error) } } } private static func printError(_ error: ErrorProtocol) -> Void { print("Error: \(error)") } private func printHeader() { var header = "\n" header += "\n" header += "\n" header += " _____\n" header += " ,.-``-._.-``-., /__ / ___ _ ______\n" header += " |`-._,.-`-.,_.-`| / / / _ \\ | /| / / __ \\\n" header += " | |ˆ-. .-`| | / /__/ __/ |/ |/ / /_/ /\n" header += " `-.,| | |,.-` /____/\\___/|__/|__/\\____/ (c)\n" header += " `-.,|,.-` -----------------------------\n" header += "\n" header += "================================================================================\n" header += "Started HTTP server, listening on port \(port)." print(header) } } extension Request { var connection: Header { get { return headers.headers["connection"] ?? Header([]) } set(connection) { headers.headers["connection"] = connection } } var isKeepAlive: Bool { if version.minor == 0 { return connection.values.contains({$0.lowercased().contains("keep-alive")}) } return connection.values.contains({!$0.lowercased().contains("close")}) } } extension Response { typealias DidUpgrade = (Request, Stream) throws -> Void // Warning: The storage key has to be in sync with Zewo.HTTP's upgrade property. var didUpgrade: DidUpgrade? { get { return storage["response-connection-upgrade"] as? DidUpgrade } set(didUpgrade) { storage["response-connection-upgrade"] = didUpgrade } } }
mit
26a4c15c1fe7984cab9e67ab24c2f6e9
34.860335
328
0.565041
4.692251
false
false
false
false
OneBusAway/onebusaway-iphone
OneBusAway/ui/MapTable/Stops/StopCell.swift
2
5164
// // StopCell.swift // OneBusAway // // Created by Aaron Brethorst on 5/23/18. // Copyright © 2018 OneBusAway. All rights reserved. // import UIKit import OBAKit import SnapKit class StopCell: SelfSizingCollectionCell { var stopViewModel: StopViewModel? { didSet { guard let stop = stopViewModel else { return } nameLabel.text = stop.nameWithDirection routesLabel.text = stop.routeNames if let image = stop.image { imageView.image = image imageView.snp.updateConstraints { (make) in make.width.equalTo(16.0) } } } } override func prepareForReuse() { super.prepareForReuse() imageView.image = nil imageView.snp.updateConstraints { (make) in make.width.equalTo(0.0) } nameLabel.text = nil routesLabel.text = nil } private let nameLabel: UILabel = { let lbl = UILabel() lbl.setContentHuggingPriority(.defaultHigh, for: .vertical) lbl.setContentCompressionResistancePriority(.required, for: .vertical) return lbl }() private let routesLabel: UILabel = { let lbl = UILabel() lbl.font = OBATheme.footnoteFont lbl.setContentHuggingPriority(.defaultHigh, for: .vertical) lbl.setContentCompressionResistancePriority(.required, for: .vertical) return lbl }() private lazy var labelStack: UIStackView = { let stack = UIStackView.init(arrangedSubviews: [nameLabel, routesLabel]) stack.axis = .vertical return stack }() private lazy var labelStackWrapper: UIView = { let plainWrapper = labelStack.oba_embedInWrapperView(withConstraints: false) if #available(iOS 13.0, *) { plainWrapper.backgroundColor = .secondarySystemGroupedBackground } else { plainWrapper.backgroundColor = .white } labelStack.snp.makeConstraints { (make) in make.height.greaterThanOrEqualTo(44) make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: OBATheme.defaultPadding, bottom: OBATheme.defaultPadding, right: OBATheme.defaultPadding)) } return plainWrapper }() private let chevronWrapper: UIView = { let chevronImage = UIImageView(image: #imageLiteral(resourceName: "chevron")) if #available(iOS 13.0, *) { chevronImage.tintColor = .systemGray2 } else { chevronImage.tintColor = .darkGray } let chevronWrapper = chevronImage.oba_embedInWrapperView(withConstraints: false) if #available(iOS 13.0, *) { chevronWrapper.backgroundColor = .secondarySystemGroupedBackground } else { chevronWrapper.backgroundColor = .white } chevronImage.snp.makeConstraints { make in make.height.equalTo(14) make.width.equalTo(8) make.leading.trailing.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: OBATheme.defaultPadding)) make.centerY.equalToSuperview() } return chevronWrapper }() private let imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit if #available(iOS 13.0, *) { imageView.tintColor = .label } return imageView }() private let separator: CALayer = { let layer = CALayer() layer.backgroundColor = UIColor(red: 200 / 255.0, green: 199 / 255.0, blue: 204 / 255.0, alpha: 1).cgColor return layer }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = OBATheme.mapTableBackgroundColor let imageViewWrapper = imageView.oba_embedInWrapperView(withConstraints: false) if #available(iOS 13.0, *) { imageViewWrapper.backgroundColor = .secondarySystemGroupedBackground } else { imageViewWrapper.backgroundColor = .white } imageView.snp.remakeConstraints { make in make.width.equalTo(0.0) make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: OBATheme.defaultPadding, bottom: 0, right: 0)) } let outerStack = UIStackView.oba_horizontalStack(withArrangedSubviews: [imageViewWrapper, labelStackWrapper, chevronWrapper]) let cardWrapper = outerStack.oba_embedInCardWrapper() contentView.addSubview(cardWrapper) cardWrapper.snp.makeConstraints { make in make.edges.equalToSuperview().inset(StopCell.leftRightInsets) } contentView.layer.addSublayer(separator) } override func layoutSubviews() { super.layoutSubviews() let bounds = contentView.bounds let height: CGFloat = 0.5 let sideInset = OBATheme.defaultEdgeInsets.left separator.frame = CGRect(x: sideInset, y: bounds.height - height, width: bounds.width - (2 * sideInset), height: height) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
f68d335b264c21f7c71ecaa847b3f600
31.471698
165
0.637614
4.866164
false
false
false
false
hoorace/Swift-Font-Awesome
Swift-Font-Awesome/ViewController.swift
1
3830
// // ViewController.swift // Swift-Font-Awesome // // Created by longhao on 15/7/17. // Copyright (c) 2015年 longhao. All rights reserved. // import UIKit class ViewController: UIViewController { private var leftButton: UIBarButtonItem! private var rightButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() initNavigation() initUILabel() initButton() initImage() // Do any additional setup after loading the view, typically from a nib. } func initUILabel(){ let label = UILabel(frame: CGRectMake(50, 70, 100, 25)) label.text = " Medium" label.fa = Fa.Medium self.view.addSubview(label) let like = UILabel(frame: CGRectMake(150, 70, 100, 25)) like.faTextAlignment = .Left like.text = " Like" like.fa = Fa.Heart like.textColor = UIColor.redColor() self.view.addSubview(like) let world = UILabel(frame: CGRectMake(50, 120, 300, 50)) world.faTextAlignment = .Right world.text = "Medium " world.fa = Fa.Medium world.font = FaType.X3.font self.view.addSubview(world) } func initButton() { let button = UIButton(frame: CGRectMake(50, 220, 120, 30)) button.backgroundColor = UIColor.clearColor() button.layer.cornerRadius = 5 button.layer.borderWidth = 1 button.layer.borderColor = UIColor.blueColor().CGColor button.titleLabel?.text = " Submit" button.setTitleColor(UIColor.blueColor(), forState: .Normal) button.faTextAlignment = .Left button.fa(Fa.Comment, forState: .Normal) self.view.addSubview(button) } func initImage(){ let image = UIImage(faCircle: Fa.Twitter, imageSize: 48, color: .whiteColor(), circleColor: .orangeColor(), backgroundColor: .clearColor()) let imageView = UIImageView(frame: CGRectMake(50, 300, 64, 64)) imageView.image = image self.view.addSubview(imageView) let image1 = UIImage(faSquare: Fa.Twitter, imageSize: 48, color: .orangeColor(), circleColor: .orangeColor(), backgroundColor: .clearColor()) let imageView1 = UIImageView(frame: CGRectMake(150, 300, 64, 64)) imageView1.image = image1 self.view.addSubview(imageView1) let image2 = UIImage(fa: Fa.Twitter , imageSize: 48, color: .blueColor(), backgroundColor: .clearColor()) let imageView2 = UIImageView(frame: CGRectMake(250, 300, 64, 64)) imageView2.image = image2 self.view.addSubview(imageView2) } func initNavigation(){ self.view.backgroundColor = UIColor.whiteColor() self.title = "Swift Font Awesome" leftButton = UIBarButtonItem(title: "", style: .Plain, target: self, action: "onClickMyButton:") leftButton.fa = Fa.Backward rightButton = UIBarButtonItem(title: " List", style: .Plain, target: self, action: "onClickMyButton:") rightButton.fa = Fa.Bars leftButton.tag = 1 rightButton.tag = 2 self.navigationItem.leftBarButtonItem = leftButton self.navigationItem.rightBarButtonItem = rightButton } internal func onClickMyButton(sender: UIButton){ switch(sender.tag){ case 1: self.view.backgroundColor = UIColor.whiteColor() case 2: self.view.backgroundColor = UIColor.orangeColor() default: print("") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
beb9a46697d08353723e2a836704944d
31.168067
149
0.606322
4.64
false
false
false
false
FabrizioBrancati/BFKit-Swift
Sources/BFKit/Apple/UIKit/UIDevice+Extensions.swift
1
19331
// // UIDevice+Extensions.swift // BFKit-Swift // // The MIT License (MIT) // // Copyright (c) 2015 - 2019 Fabrizio Brancati. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import UIKit // MARK: - Global variables /// Used to store BFAPNSIdentifier in defaults. private let BFAPNSIdentifierDefaultsKey = "BFAPNSIdentifier" /// Used to store BFDeviceIdentifier in defaults. internal let BFDeviceIdentifierDefaultsKey = "BFDeviceIdentifier" // MARK: - Global functions /// Compare OS versions. /// /// - Parameter version: Version, like "9.0". /// - Returns: Returns true if equal, otherwise false. public func osVersionEqual(_ version: String) -> Bool { UIDevice.current.systemVersion.compare(version, options: .numeric) == .orderedSame } /// Compare OS versions. /// /// - Parameter version: Version, like "9.0". /// - Returns: Returns true if greater, otherwise false. public func osVersionGreaterThan(_ version: String) -> Bool { UIDevice.current.systemVersion.compare(version, options: .numeric) == .orderedDescending } /// Compare OS versions. /// /// - Parameter version: Version, like "9.0". /// - Returns: Returns true if greater or equal, otherwise false. public func osVersionGreaterThanOrEqual(_ version: String) -> Bool { UIDevice.current.systemVersion.compare(version, options: .numeric) != .orderedAscending } /// Compare OS versions. /// /// - Parameter version: Version, like "9.0". /// - Returns: Returns true if less, otherwise false. public func osVersionLessThan(_ version: String) -> Bool { UIDevice.current.systemVersion.compare(version, options: .numeric) == .orderedAscending } /// Compare OS versions. /// /// - Parameter version: Version, like "9.0". /// - Returns: Returns true if less or equal, otherwise false. public func osVersionLessThanOrEqual(_ version: String) -> Bool { UIDevice.current.systemVersion.compare(version, options: .numeric) != .orderedDescending } // MARK: - UIDevice extension /// This extesion adds some useful functions to UIDevice public extension UIDevice { // MARK: - Variables /// Get OS version string. static var osVersion: String { UIDevice.current.systemVersion } /// Returns OS version without subversions. /// /// Example: 9. static var osMajorVersion: Int { let subVersion = UIDevice.current.systemVersion.substring(to: ".") guard let intSubVersion = Int(subVersion) else { return 0 } return intSubVersion } /// Returns device platform string. /// /// Example: "iPhone7,2". /// /// - Returns: Returns the device platform string. static var hardwareModel: String { var name: [Int32] = [CTL_HW, HW_MACHINE] var nameCopy = name var size: Int = 2 sysctl(&nameCopy, 2, nil, &size, &name, 0) var hwMachine = [CChar](repeating: 0, count: Int(size)) sysctl(&nameCopy, 2, &hwMachine, &size, &name, 0) let hardware = String(cString: hwMachine) return hardware } // swiftlint:disable switch_case_on_newline /// Returns the user-friendly device platform string. /// More info [here](https://www.theiphonewiki.com/wiki/Models). /// /// Example: "iPad Air (Cellular)". /// /// - Returns: Returns the user-friendly device platform string. static var detailedModel: String { let platform: String = hardwareModel switch platform { // iPhone 2G case "iPhone1,1": return "iPhone 2G" // iPhone 3G case "iPhone1,2": return "iPhone 3G" // iPhone 3GS case "iPhone2,1": return "iPhone 3GS" // iPhone 4 case "iPhone3,1": return "iPhone 4" case "iPhone3,2": return "iPhone 4" case "iPhone3,3": return "iPhone 4" // iPhone 4S case "iPhone4,1": return "iPhone 4S" // iPhone 5 case "iPhone5,1": return "iPhone 5" case "iPhone5,2": return "iPhone 5" // iPhone 5c case "iPhone5,3": return "iPhone 5c" case "iPhone5,4": return "iPhone 5c" // iPhone 5s case "iPhone6,1": return "iPhone 5s" case "iPhone6,2": return "iPhone 5s" // iPhone 6 / 6 Plus case "iPhone7,1": return "iPhone 6 Plus" case "iPhone7,2": return "iPhone 6" // iPhone 6s / 6s Plus case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" // iPhone SE case "iPhone8,4": return "iPhone SE" // iPhone 7 / 7 Plus case "iPhone9,1": return "iPhone 7" case "iPhone9,2": return "iPhone 7 Plus" case "iPhone9,3": return "iPhone 7" case "iPhone9,4": return "iPhone 7 Plus" // iPhone 8 / 8 Plus case "iPhone10,1": return "iPhone 8" case "iPhone10,2": return "iPhone 8 Plus" case "iPhone10,4": return "iPhone 8" case "iPhone10,5": return "iPhone 8 Plus" // iPhone X case "iPhone10,3": return "iPhone X" case "iPhone10,6": return "iPhone X" // iPhone XS / iPhone XS Max case "iPhone11,2": return "iPhone XS" case "iPhone11,4": return "iPhone XS Max" case "iPhone11,6": return "iPhone XS Max" // iPhone XR case "iPhone11,8": return "iPhone XR" // iPhone 11 case "iPhone12,1": return "iPhone 11" // iPhone 11 Pro Max case "iPhone12,3": return "iPhone 11 Pro" // iPhone 11 Pro case "iPhone12,5": return "iPhone 11 Pro Max" // iPod touch case "iPod1,1": return "iPod touch (1st generation)" case "iPod2,1": return "iPod touch (2nd generation)" case "iPod3,1": return "iPod touch (3rd generation)" case "iPod4,1": return "iPod touch (4th generation)" case "iPod5,1": return "iPod touch (5th generation)" case "iPod7,1": return "iPod touch (6th generation)" case "iPod9,1": return "iPod touch (7th generation)" // iPad / iPad Air case "iPad1,1": return "iPad" case "iPad2,1": return "iPad 2" case "iPad2,2": return "iPad 2" case "iPad2,3": return "iPad 2" case "iPad2,4": return "iPad 2" case "iPad3,1": return "iPad 3" case "iPad3,2": return "iPad 3" case "iPad3,3": return "iPad 3" case "iPad3,4": return "iPad 4" case "iPad3,5": return "iPad 4" case "iPad3,6": return "iPad 4" case "iPad4,1": return "iPad Air" case "iPad4,2": return "iPad Air" case "iPad4,3": return "iPad Air" case "iPad5,3": return "iPad Air 2" case "iPad5,4": return "iPad Air 2" case "iPad6,11": return "iPad Air 2" case "iPad6,12": return "iPad Air 2" case "iPad11,3": return "iPad Air (3rd generation)" case "iPad11,4": return "iPad Air (3rd generation)" // iPad mini case "iPad2,5": return "iPad mini" case "iPad2,6": return "iPad mini" case "iPad2,7": return "iPad mini" case "iPad4,4": return "iPad mini 2" case "iPad4,5": return "iPad mini 2" case "iPad4,6": return "iPad mini 2" case "iPad4,7": return "iPad mini 3" case "iPad4,8": return "iPad mini 3" case "iPad4,9": return "iPad mini 3" case "iPad5,1": return "iPad mini 4" case "iPad5,2": return "iPad mini 4" case "iPad11,1": return "iPad mini (5th generation)" case "iPad11,2": return "iPad mini (5th generation)" // iPad Pro 9.7 case "iPad6,3": return "iPad Pro (9.7-inch)" case "iPad6,4": return "iPad Pro (9.7-inch)" // iPad Pro 10.5 case "iPad7,3": return "iPad Pro (10.5-inch)" case "iPad7,4": return "iPad Pro (10.5-inch)" // iPad Pro 11 case "iPad8,1": return "iPad Pro (11-inch)" case "iPad8,2": return "iPad Pro (11-inch)" case "iPad8,3": return "iPad Pro (11-inch)" case "iPad8,4": return "iPad Pro (11-inch)" // iPad Pro 12.9 case "iPad6,7": return "iPad Pro (12.9-inch)" case "iPad6,8": return "iPad Pro (12.9-inch)" case "iPad7,1": return "iPad Pro (12.9-inch, 2nd generation)" case "iPad7,2": return "iPad Pro (12.9-inch, 2nd generation)" case "iPad8,5": return "iPad Pro (12.9-inch, 3rd generation)" case "iPad8,6": return "iPad Pro (12.9-inch, 3rd generation)" case "iPad8,7": return "iPad Pro (12.9-inch, 3rd generation)" case "iPad8,8": return "iPad Pro (12.9-inch, 3rd generation)" // Apple TV case "AppleTV2,1": return "Apple TV (2nd generation)" case "AppleTV3,1": return "Apple TV (3rd generation)" case "AppleTV3,2": return "Apple TV (3rd generation)" case "AppleTV5,3": return "Apple TV (4th generation)" case "AppleTV6,2": return "Apple TV 4K" // Simulator case "i386", "x86_64": return "Simulator" default: return "Unknown" } } // swiftlint:enable switch_case_on_newline /// Returns current device CPU frequency. static var cpuFrequency: Int { getSysInfo(HW_CPU_FREQ) } /// Returns current device BUS frequency. static var busFrequency: Int { getSysInfo(HW_TB_FREQ) } /// Returns device RAM size. static var ramSize: Int { getSysInfo(HW_MEMSIZE) } /// Returns device CPUs number. static var cpusNumber: Int { getSysInfo(HW_NCPU) } /// Returns device total memory. static var totalMemory: Int { getSysInfo(HW_PHYSMEM) } /// Returns current device non-kernel memory. static var userMemory: Int { getSysInfo(HW_USERMEM) } /// Retruns if current device is running in low power mode. @available(iOS 9.0, *) static var isLowPowerModeEnabled: Bool { ProcessInfo.processInfo.isLowPowerModeEnabled } /// Low power mode observer. private static var lowPowerModeObserver = false // MARK: - Functions /// Executes a block everytime low power mode is enabled o disabled. /// /// - Parameter block: Block to be executed. @objc @available(iOS 9.0, *) static func lowPowerModeChanged(_ block: @escaping (_ isLowPowerModeEnabled: Bool) -> Void) { if !lowPowerModeObserver { NotificationCenter.default.addObserver(self, selector: #selector(lowPowerModeChanged(_:)), name: .NSProcessInfoPowerStateDidChange, object: nil) lowPowerModeObserver = true } block(UIDevice.isLowPowerModeEnabled) } /// Check if current device is an iPhone. /// /// - Returns: Returns true if it is an iPhone, otherwise false. static func isPhone() -> Bool { hardwareModel.substring(to: 6) == "iPhone" } /// Check if current device is an iPad. /// /// - Returns: Returns true if it is an iPad, otherwise false. static func isPad() -> Bool { hardwareModel.substring(to: 4) == "iPad" } /// Check if current device is an iPod. /// /// - Returns: Returns true if it is an iPod, otherwise false. static func isPod() -> Bool { hardwareModel.substring(to: 4) == "iPod" } /// Check if current device is an Apple TV. /// /// - Returns: Returns true if it is an Apple TV, otherwise false. static func isTV() -> Bool { hardwareModel.substring(to: 7) == "AppleTV" } /// Check if current device is an Applw Watch. /// /// - Returns: Returns true if it is an Apple Watch, otherwise false. static func isWatch() -> Bool { hardwareModel.substring(to: 5) == "Watch" } /// Check if current device is a Simulator. /// /// - Returns: Returns true if it is a Simulator, otherwise false. static func isSimulator() -> Bool { detailedModel == "Simulator" } /// Returns if current device is jailbroken. /// /// - Returns: Returns true if current device is jailbroken, otherwise false. static func isJailbroken() -> Bool { let canReadBinBash = FileManager.default.fileExists(atPath: "/bin/bash") if let cydiaURL = URL(string: "cydia://"), let canOpenCydia = (UIApplication.value(forKey: "sharedApplication") as? UIApplication)?.canOpenURL(cydiaURL) { return canOpenCydia || canReadBinBash } else { return canReadBinBash } } /// Returns system uptime. /// /// - Returns: eturns system uptime. static func uptime() -> TimeInterval { ProcessInfo.processInfo.systemUptime } /// Returns sysyem uptime as Date. /// /// - Returns: Returns sysyem uptime as Date. static func uptimeDate() -> Date { Date(timeIntervalSinceNow: -uptime()) } /// Returns current device total disk space /// /// - Returns: Returns current device total disk space. static func totalDiskSpace() -> NSNumber { do { let attributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory()) return attributes[.systemSize] as? NSNumber ?? NSNumber(value: 0.0) } catch { return NSNumber(value: 0.0) } } /// Returns current device free disk space. /// /// - Returns: Returns current device free disk space. static func freeDiskSpace() -> NSNumber { do { let attributes = try FileManager.default.attributesOfFileSystem(forPath: NSHomeDirectory()) return attributes[.systemFreeSize] as? NSNumber ?? NSNumber(value: 0.0) } catch { return NSNumber(value: 0.0) } } /// Used to the system info. /// /// - Parameter typeSpecifier: Type of system info. /// - Returns: Return sysyem info. fileprivate static func getSysInfo(_ typeSpecifier: Int32) -> Int { var name: [Int32] = [CTL_HW, typeSpecifier] var nameCopy = name var size: Int = 2 sysctl(&nameCopy, 2, nil, &size, &name, 0) var results: Int = 0 sysctl(&nameCopy, 2, &results, &size, &name, 0) return results } /// When `save` is false, a new UUID will be created every time. /// When `save` is true, a new UUID will be created and saved in the user defatuls. /// It will be retrieved on next calls. /// /// - Parameters: /// - save: If true the UUID will be saved, otherview not. /// - force: If true a new UUID will be forced, even there is a saved one. /// - Returns: Returns the created (`save` = false`) or retrieved (`save` = true) UUID String. static func generateUniqueIdentifier(save: Bool = false, force: Bool = false) -> String { if save { let defaults = UserDefaults.standard guard !force else { let identifier = UUID().uuidString defaults.set(identifier, forKey: BFDeviceIdentifierDefaultsKey) defaults.synchronize() return identifier } guard let identifier = defaults.string(forKey: BFDeviceIdentifierDefaultsKey) else { let identifier = UUID().uuidString defaults.set(identifier, forKey: BFDeviceIdentifierDefaultsKey) defaults.synchronize() return identifier } return identifier } return UUID().uuidString } /// Save the unique identifier or update it if there is and it is changed. /// Is useful for push notification to know if the unique identifier has changed and needs to be sent to server. /// /// - Parameters: /// - uniqueIdentifier: The unique identifier to save or update if needed. Must be Data or String type. /// - completion: The execution block that know if the unique identifier is valid and has to be updated. /// You have to handle the case if it is valid and the update is needed or not. /// /// - isValid: Returns if the APNS token is valid. /// - needsUpdate: Returns if the APNS token needsAnUpdate. /// - oldUUID: Returns the old UUID, if present. May be nil. /// - newUUID: Returns the new UUID. static func saveAPNSIdentifier(_ uniqueIdentifier: Any, completion: @escaping (_ isValid: Bool, _ needsUpdate: Bool, _ oldUUID: String?, _ newUUID: String) -> Void) { var newUUID: String = "" var oldUUID: String? var isValid = false, needsUpdate = false if uniqueIdentifier is Data, let data: Data = uniqueIdentifier as? Data, let newUUIDData = data.utf8() { isValid = newUUIDData.isUUIDForAPNS() } else if uniqueIdentifier is String, let string: String = uniqueIdentifier as? String { newUUID = string.readableUUID() isValid = newUUID.isUUIDForAPNS() } if isValid { let defaults = UserDefaults.standard oldUUID = defaults.string(forKey: BFAPNSIdentifierDefaultsKey) if oldUUID == nil || oldUUID != newUUID { defaults.set(newUUID, forKey: BFAPNSIdentifierDefaultsKey) defaults.synchronize() needsUpdate = true } } completion(isValid, needsUpdate, oldUUID, newUUID) } }
mit
e9821983b162264c78dcb189129e3708
38.052525
170
0.584346
4.191457
false
false
false
false
moongift/NCMBiOSTwitter
NCMBiOS_Twitter/MasterViewController.swift
1
7223
// // MasterViewController.swift // NCMBiOS_Twitter // // Created by naokits on 7/4/15. // Copyright (c) 2015 Naoki Tsutsui. All rights reserved. // import UIKit class MasterViewController: UITableViewController { /// TODOを格納する配列 var objects = [Todo]() override func awakeFromNib() { super.awakeFromNib() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if let user = NCMBUser.currentUser() { self.fetchAllTodos() } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if let user = NCMBUser.currentUser() { println("ログイン中: \(user)") } else { println("ログインしていない") self.performSegueWithIdentifier("toLogin", sender: self) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // ------------------------------------------------------------------------ // MARK: - Segues // ------------------------------------------------------------------------ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "goEditTodo" { if let indexPath = self.tableView.indexPathForSelectedRow() { let object = self.objects[indexPath.row] if let dvc = segue.destinationViewController as? DetailViewController { dvc.detailItem = object dvc.updateButton.title = "更新" } } } else if segue.identifier == "goAddTodo" { (segue.destinationViewController as! DetailViewController).updateButton.title = "追加" } else if segue.identifier == "toLogin" { println("ログアウトしてログイン画面に遷移します") NCMBUser.logOut() } else { // 遷移先が定義されていない } } /// TODO登録/編集画面から戻ってきた時の処理を行います。 @IBAction func unwindFromTodoEdit(segue:UIStoryboardSegue) { println("---- unwindFromTodoEdit: \(segue.identifier)") let svc = segue.sourceViewController as! DetailViewController if count(svc.todoTitle.text) < 3 { return } if svc.detailItem == nil { println("TODOオブジェクトが存在しないので、新規とみなします。") println("\(svc.todoTitle.text)") self.addTodoWithTitle(svc.todoTitle.text) } else { println("更新処理") svc.detailItem?.title = svc.todoTitle.text svc.detailItem?.saveInBackgroundWithBlock({ (error: NSError!) -> Void in self.tableView.reloadData() }) } } /// ログイン画面から戻ってきた時の処理を行います。 @IBAction func unwindFromLogin(segue:UIStoryboardSegue) { // ログインが終了したら強制的にTODO一覧を取得 self.objects = [Todo]() self.fetchAllTodos() } // ------------------------------------------------------------------------ // MARK: - Table View // ------------------------------------------------------------------------ override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell let todo = objects[indexPath.row] cell.textLabel!.text = todo.objectForKey("title") as? String cell.textLabel!.text = todo.title return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { objects.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } // ------------------------------------------------------------------------ // MARK: Methods for Data Source // ------------------------------------------------------------------------ /// 全てのTODO情報を取得し、プロパティに格納します /// /// :param: None /// :returns: None func fetchAllTodos() { // クエリを生成 let query = Todo.query() as NCMBQuery // タイトルにデータが含まれないものは除外 query.whereKeyExists("title") // 登録日の降順で取得 query.orderByDescending("createDate") // 取得件数の指定 query.limit = 20 query.findObjectsInBackgroundWithBlock({(NSArray todos, NSError error) in if (error == nil) { println("登録件数: \(todos.count)") for todo in todos { println("--- \(todo.objectId): \(todo.title)") } self.objects = todos as! [Todo] // NSArray -> Swift Array self.tableView.reloadData() } else { println("Error: \(error)") } }) } /// 新規にTODOを追加します /// /// :param: title TODOのタイトル /// :returns: None func addTodoWithTitle(title: String) { let todo = Todo.object() as! Todo todo.title = title todo.ACL = NCMBACL(user: NCMBUser.currentUser()) // 非同期で保存 todo.saveInBackgroundWithBlock { (error: NSError!) -> Void in if error == nil { println("新規TODOの保存成功。表示の更新などを行う。") self.insertNewTodoObject(todo) } else { println("新規TODOの保存に失敗しました: \(error)") } } } /// TODOをDataSourceに追加して、表示を更新します /// /// :param: todo TODOオブジェクト(NCMBObject) /// :returns: None func insertNewTodoObject(todo: Todo!) { self.objects.insert(todo, atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) self.tableView.reloadData() } }
mit
4f66148284cf15f1c4a6395237b064fc
33.419689
157
0.549902
5.141641
false
false
false
false