repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
nunosans/currency
Currency/UI Classes/CalculatorSwitchButton.swift
1
2108
// // CalculatorSwitchButton.swift // Currency // // Created by Nuno Coelho Santos on 13/03/2016. // Copyright © 2016 Nuno Coelho Santos. All rights reserved. // import Foundation import UIKit class CalculatorSwitchButton: UIButton { let borderColor: CGColor! = UIColor(red:0.85, green:0.85, blue:0.85, alpha:1.00).cgColor let normalStateColor: CGColor! = UIColor(red:0.98, green:0.98, blue:0.98, alpha:1.00).cgColor let highlightStateColor: CGColor! = UIColor(red:1.00, green:0.62, blue:0.00, alpha:1.00).cgColor required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.setImage(UIImage(named: "buttonSwitchIconHighlighted.png"), for: .highlighted) self.layer.borderWidth = 0.25 self.layer.borderColor = borderColor self.layer.masksToBounds = true self.backgroundColor = UIColor(cgColor: normalStateColor) } override var isHighlighted: Bool { get { return super.isHighlighted } set { if newValue { let fadeIn = CABasicAnimation(keyPath: "backgroundColor") fadeIn.fromValue = normalStateColor fadeIn.toValue = highlightStateColor fadeIn.duration = 0.12 fadeIn.autoreverses = false fadeIn.repeatCount = 1 self.layer.add(fadeIn, forKey: "fadeIn") self.backgroundColor = UIColor(cgColor: highlightStateColor) } else { let fadeOut = CABasicAnimation(keyPath: "backgroundColor") fadeOut.fromValue = highlightStateColor fadeOut.toValue = normalStateColor fadeOut.duration = 0.12 fadeOut.autoreverses = false fadeOut.repeatCount = 1 self.layer.add(fadeOut, forKey: "fadeOut") self.backgroundColor = UIColor(cgColor: normalStateColor) } super.isHighlighted = newValue } } }
mit
7696b6c51fccf1907f41dfd4742af5aa
33.540984
100
0.587091
4.713647
false
false
false
false
Pocketbrain/nativeadslib-ios
PocketMediaNativeAds/Core/NativeAdsRequest.swift
1
7670
// // AsynchronousRequest.swift // DiscoveryApp // // Created by Carolina Barreiro Cancela on 28/05/15. // Copyright (c) 2015 Pocket Media. All rights reserved. // import UIKit import AdSupport /* NativeAdsRequest is a controller class that will do a network request and call a instance of NativeAdsConnectionDelegate based on the results. */ open class NativeAdsRequest: NSObject, NSURLConnectionDelegate, UIWebViewDelegate { /// Object to notify about the updates related with the ad request open var delegate: NativeAdsConnectionDelegate? /// Needed to identify the ad requests to the server open var adPlacementToken: String? /// Check whether advertising tracking is limited open var advertisingTrackingEnabled: Bool? = false /// URL session used to do network requests. open var session: URLSession? /** NativeAdsRequest is a controller class that will do a network request and call a instance of NativeAdsConnectionDelegate based on the results. - parameter withAdPlacementToken: The placement token received from http://third-party.pmgbrain.com/ - paramter delegate: instance of NativeAdsConnectionDelegate that will be informed about the network call results. - parameter advertisingTrackingEnabled: Boolean defining if the tracking token is enabled. If none specified system boolean is used. - parameter session: A instance of URLSession to the network requests with. */ @objc public init(withAdPlacementToken: String?, delegate: NativeAdsConnectionDelegate? ) { super.init() self.adPlacementToken = withAdPlacementToken self.delegate = delegate self.advertisingTrackingEnabled = ASIdentifierManager.shared().isAdvertisingTrackingEnabled self.session = URLSession.shared } // not objc compatible because of the usage of URLSessionProtocol public init(adPlacementToken: String?, delegate: NativeAdsConnectionDelegate?, advertisingTrackingEnabled: Bool = ASIdentifierManager.shared().isAdvertisingTrackingEnabled, session: URLSession = URLSession.shared ) { super.init() self.adPlacementToken = adPlacementToken self.delegate = delegate self.advertisingTrackingEnabled = advertisingTrackingEnabled self.session = session } /** Method used to retrieve native ads which are later accessed by using the delegate. - parameter limit: Limit on how many native ads are to be retrieved. - parameter imageType: Image Type is used to specify what kind of image type will get requested. */ @objc open func retrieveAds(_ limit: UInt, imageType: EImageType = EImageType.allImages) { let nativeAdURL = getNativeAdsURL(self.adPlacementToken, limit: limit, imageType: imageType) Logger.debugf("Invoking: %@", nativeAdURL) if let url = URL(string: nativeAdURL) { let task = self.session!.dataTask(with: url, completionHandler: receivedAds) task.resume() } } /** Method is called as a completionHandler when we hear back from the server - parameter data: The NSData object which contains the server response - parameter response: The NSURLResponse type which indicates what type of response we got back. - parameter error: The error object tells us if there was an error during the external request. */ internal func receivedAds(_ data: Data?, response: URLResponse?, error: Error?) { if error != nil { delegateDidReceiveError(error!) return } if data == nil { delegateDidReceiveError(NSError(domain: "mobi.pocketmedia.nativeads", code: -1, userInfo: ["Invalid server response received: data is a nil value.": NSLocalizedDescriptionKey])) return } if let json: NSArray = (try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)) as? NSArray { mapAds(json) } else { delegateDidReceiveError(NSError(domain: "mobi.pocketmedia.nativeads", code: -1, userInfo: ["Invalid server response received: Not json.": NSLocalizedDescriptionKey])) } } /** This function wraps around the call to the delegate. It will make sure that the call to delegate is called on the main thread. Because there is a high likelyhood that the user will do UI changes the moment the call comes in. - parameter error: The error sent to the delegate. */ private func delegateDidReceiveError(_ error: Error) { DispatchQueue.main.async { self.delegate?.didReceiveError(error) } } /** This function wraps around the call to the delegate. It will make sure that the call to delegate is called on the main thread. Because there is a high likelyhood that the user will do UI changes the moment the call comes in. - parameter nativeads: The result of ads sent to the delegate. */ private func delegateDidReceiveResults(_ nativeAds: [NativeAd]) { DispatchQueue.main.async { self.delegate?.didReceiveResults(nativeAds) } } /** This method takes charge of mapping the NSArray into an array of nativeAds instances and call the NativeAdsConnectionDelegate with an error or results method. Called from receivedAds. - jsonArray: The json array. */ internal func mapAds(_ jsonArray: NSArray) { let ads = jsonArray.filter({ ($0 as? Dictionary<String, Any>) != nil }) var nativeAds: [NativeAd] = [] for ad in ads { do { if let adDict = ad as? Dictionary<String, Any> { let ad = try NativeAd(adDictionary: adDict, adPlacementToken: self.adPlacementToken!) nativeAds.append(ad) } } catch let error as NSError { delegateDidReceiveError(error) return } } if nativeAds.count > 0 { delegateDidReceiveResults(nativeAds) } else { let userInfo = ["No ads available from server": NSLocalizedDescriptionKey] let error = NSError(domain: "mobi.pocketmedia.nativeads", code: -1, userInfo: userInfo) delegateDidReceiveError(error) } } /** This method returns the UUID of the device. */ fileprivate func provideIdentifierForAdvertisingIfAvailable() -> String? { return ASIdentifierManager.shared().advertisingIdentifier?.uuidString } /** Returns the API URL to invoke to retrieve ads */ internal func getNativeAdsURL(_ placementKey: String?, limit: UInt, imageType: EImageType) -> String { let token = provideIdentifierForAdvertisingIfAvailable() let baseUrl = NativeAdsConstants.NativeAds.baseURL // Version var apiUrl = baseUrl + "&req_version=002" // OS apiUrl += "&os=ios" // Limit apiUrl += "&limit=\(limit)" // Version apiUrl += "&version=\(NativeAdsConstants.Device.iosVersion)" // Model apiUrl += "&model=\(NativeAdsConstants.Device.model)" // Token apiUrl += "&token=\(token!)" // Placement key apiUrl += "&placement_key=\(placementKey!)" // Image type apiUrl += "&image_type=\(imageType.description)" if advertisingTrackingEnabled == nil || advertisingTrackingEnabled == false { apiUrl = apiUrl + "&optout=1" } return apiUrl } }
mit
74991889d4efdb9e0cefa48413b455ab
41.611111
229
0.663364
4.977287
false
false
false
false
p4bloch/LocationManager
LocationManager.swift
1
24312
// // LocationManager.swift // // // Created by Jimmy Jose on 14/08/14. // // // 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 CoreLocation import MapKit typealias LMReverseGeocodeCompletionHandler = ((reverseGecodeInfo:NSDictionary?,placemark:CLPlacemark?, error:String?)->Void)? typealias LMGeocodeCompletionHandler = ((gecodeInfo:NSDictionary?,placemark:CLPlacemark?, error:String?)->Void)? typealias LMLocationCompletionHandler = ((latitude:Double, longitude:Double, status:String, verboseMessage:String, error:String?)->())? // Todo: Keep completion handler differerent for all services, otherwise only one will work enum GeoCodingType{ case Geocoding case ReverseGeocoding } class LocationManager: NSObject,CLLocationManagerDelegate { /* Private variables */ private var completionHandler:LMLocationCompletionHandler private var reverseGeocodingCompletionHandler:LMReverseGeocodeCompletionHandler private var geocodingCompletionHandler:LMGeocodeCompletionHandler private var locationStatus = NSLocalizedString("Calibrating", comment: "")// to pass in handler private var locationManager: CLLocationManager! private var verboseMessage = NSLocalizedString("Calibrating", comment: "") private let verboseMessageDictionary = [CLAuthorizationStatus.NotDetermined:NSLocalizedString("You have not yet made a choice with regards to this application.", comment: ""), CLAuthorizationStatus.Restricted:NSLocalizedString("This application is not authorized to use location services. Due to active restrictions on location services, the user cannot change this status, and may not have personally denied authorization.", comment: ""), CLAuthorizationStatus.Denied:NSLocalizedString("You have explicitly denied authorization for this application, or location services are disabled in Settings.", comment: ""), CLAuthorizationStatus.AuthorizedAlways:NSLocalizedString("App is Authorized to always use location services.", comment: ""),CLAuthorizationStatus.AuthorizedWhenInUse:NSLocalizedString("You have granted authorization to use your location only when the app is visible to you.", comment: "")] var delegate:LocationManagerDelegate? = nil var latitude:Double = 0.0 var longitude:Double = 0.0 var latitudeAsString:String = "" var longitudeAsString:String = "" var lastKnownLatitude:Double = 0.0 var lastKnownLongitude:Double = 0.0 var lastKnownLatitudeAsString:String = "" var lastKnownLongitudeAsString:String = "" var keepLastKnownLocation:Bool = true var hasLastKnownLocation:Bool = true var autoUpdate:Bool = false var showVerboseMessage = false var isRunning = false class var sharedInstance : LocationManager { struct Static { static let instance : LocationManager = LocationManager() } return Static.instance } private override init(){ super.init() if !autoUpdate { autoUpdate = !CLLocationManager.significantLocationChangeMonitoringAvailable() } } private func resetLatLon(){ latitude = 0.0 longitude = 0.0 latitudeAsString = "" longitudeAsString = "" } private func resetLastKnownLatLon(){ hasLastKnownLocation = false lastKnownLatitude = 0.0 lastKnownLongitude = 0.0 lastKnownLatitudeAsString = "" lastKnownLongitudeAsString = "" } func startUpdatingLocationWithCompletionHandler(completionHandler:((latitude:Double, longitude:Double, status:String, verboseMessage:String, error:String?)->())? = nil){ self.completionHandler = completionHandler initLocationManager() } func startUpdatingLocation(){ initLocationManager() } func stopUpdatingLocation(){ if autoUpdate { locationManager.stopUpdatingLocation() } else { locationManager.stopMonitoringSignificantLocationChanges() } resetLatLon() if !keepLastKnownLocation { resetLastKnownLatLon() } } private func initLocationManager() { // App might be unreliable if someone changes autoupdate status in between and stops it locationManager = CLLocationManager() locationManager.delegate = self // locationManager.locationServicesEnabled locationManager.desiredAccuracy = kCLLocationAccuracyBest if NSString(string: UIDevice.currentDevice().systemVersion).doubleValue >= 8 { //locationManager.requestAlwaysAuthorization() // add in plist NSLocationAlwaysUsageDescription locationManager.requestWhenInUseAuthorization() // add in plist NSLocationWhenInUseUsageDescription } startLocationManger() } private func startLocationManger() { if autoUpdate { locationManager.startUpdatingLocation() } else { locationManager.startMonitoringSignificantLocationChanges() } isRunning = true } private func stopLocationManger() { if autoUpdate { locationManager.stopUpdatingLocation() } else { locationManager.stopMonitoringSignificantLocationChanges() } isRunning = false } internal func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { stopLocationManger() resetLatLon() if !keepLastKnownLocation { resetLastKnownLatLon() } var verbose = "" if showVerboseMessage {verbose = verboseMessage} completionHandler?(latitude: 0.0, longitude: 0.0, status: locationStatus, verboseMessage:verbose,error: error.localizedDescription) if (delegate != nil) && (delegate?.respondsToSelector(Selector("locationManagerReceivedError:")))! { delegate?.locationManagerReceivedError!(error.localizedDescription) } } internal func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { let arrayOfLocation = locations as NSArray let location = arrayOfLocation.lastObject as! CLLocation let coordLatLon = location.coordinate latitude = coordLatLon.latitude longitude = coordLatLon.longitude latitudeAsString = coordLatLon.latitude.description longitudeAsString = coordLatLon.longitude.description var verbose = "" if showVerboseMessage {verbose = verboseMessage} if completionHandler != nil { completionHandler?(latitude: latitude, longitude: longitude, status: locationStatus, verboseMessage:verbose, error: nil) } lastKnownLatitude = coordLatLon.latitude lastKnownLongitude = coordLatLon.longitude lastKnownLatitudeAsString = coordLatLon.latitude.description lastKnownLongitudeAsString = coordLatLon.longitude.description hasLastKnownLocation = true if delegate != nil { if (delegate?.respondsToSelector(Selector("locationFoundGetAsString:longitude:")))! { delegate?.locationFoundGetAsString!(latitudeAsString,longitude:longitudeAsString) } if (delegate?.respondsToSelector(Selector("locationFound:longitude:")))! { delegate?.locationFound(latitude,longitude:longitude) } } } internal func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { var hasAuthorised = false var verboseKey = status switch status { case CLAuthorizationStatus.Restricted: locationStatus = NSLocalizedString("Restricted Access", comment: "") case CLAuthorizationStatus.Denied: locationStatus = NSLocalizedString("Denied access", comment: "") case CLAuthorizationStatus.NotDetermined: locationStatus = NSLocalizedString("Not determined", comment: "") default: locationStatus = NSLocalizedString("Allowed access", comment: "") hasAuthorised = true } verboseMessage = verboseMessageDictionary[verboseKey]! if hasAuthorised { startLocationManger() } else { resetLatLon() if !(locationStatus == NSLocalizedString("Denied access", comment: "")) { var verbose = "" if showVerboseMessage { verbose = verboseMessage if (delegate != nil) && (delegate?.respondsToSelector(Selector("locationManagerVerboseMessage:")))! { delegate?.locationManagerVerboseMessage!(verbose) } } if completionHandler != nil { completionHandler?(latitude: latitude, longitude: longitude, status: locationStatus, verboseMessage:verbose,error: nil) } } if (delegate != nil) && (delegate?.respondsToSelector(Selector("locationManagerStatus:")))! { delegate?.locationManagerStatus!(locationStatus) } } } func reverseGeocodeLocationWithLatLon(#latitude:Double, longitude: Double,onReverseGeocodingCompletionHandler:LMReverseGeocodeCompletionHandler){ let location:CLLocation = CLLocation(latitude:latitude, longitude: longitude) reverseGeocodeLocationWithCoordinates(location, onReverseGeocodingCompletionHandler: onReverseGeocodingCompletionHandler) } func reverseGeocodeLocationWithCoordinates(coord:CLLocation, onReverseGeocodingCompletionHandler:LMReverseGeocodeCompletionHandler){ self.reverseGeocodingCompletionHandler = onReverseGeocodingCompletionHandler reverseGocode(coord) } private func reverseGocode(location:CLLocation){ let geocoder: CLGeocoder = CLGeocoder() geocoder.reverseGeocodeLocation(location, completionHandler: {(placemarks, error)->Void in if error != nil { self.reverseGeocodingCompletionHandler!(reverseGecodeInfo:nil,placemark:nil, error: error.localizedDescription) } else { if let placemark = placemarks?[0] as? CLPlacemark { var address = AddressParser() address.parseAppleLocationData(placemark) let addressDict = address.getAddressDictionary() self.reverseGeocodingCompletionHandler!(reverseGecodeInfo: addressDict,placemark:placemark,error: nil) } else { self.reverseGeocodingCompletionHandler!(reverseGecodeInfo: nil,placemark:nil,error: NSLocalizedString("No Placemarks Found!", comment: "")) return } } }) } func geocodeAddressString(#address:NSString, onGeocodingCompletionHandler:LMGeocodeCompletionHandler){ self.geocodingCompletionHandler = onGeocodingCompletionHandler geoCodeAddress(address) } private func geoCodeAddress(address:NSString){ let geocoder = CLGeocoder() geocoder.geocodeAddressString(address as String, completionHandler: {(placemarks: [AnyObject]!, error: NSError!) -> Void in if error != nil { self.geocodingCompletionHandler!(gecodeInfo:nil,placemark:nil,error: error.localizedDescription) } else { if let placemark = placemarks?[0] as? CLPlacemark { var address = AddressParser() address.parseAppleLocationData(placemark) let addressDict = address.getAddressDictionary() self.geocodingCompletionHandler!(gecodeInfo: addressDict,placemark:placemark,error: nil) } else { self.geocodingCompletionHandler!(gecodeInfo: nil,placemark:nil,error: NSLocalizedString("invalid address: \(address)", comment: "")) } } }) } func geocodeUsingGoogleAddressString(#address:NSString, onGeocodingCompletionHandler:LMGeocodeCompletionHandler){ self.geocodingCompletionHandler = onGeocodingCompletionHandler geoCodeUsignGoogleAddress(address) } private func geoCodeUsignGoogleAddress(address:NSString){ var urlString = "http://maps.googleapis.com/maps/api/geocode/json?address=\(address)&sensor=true" as NSString urlString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! performOperationForURL(urlString, type: GeoCodingType.Geocoding) } func reverseGeocodeLocationUsingGoogleWithLatLon(#latitude:Double, longitude: Double,onReverseGeocodingCompletionHandler:LMReverseGeocodeCompletionHandler){ self.reverseGeocodingCompletionHandler = onReverseGeocodingCompletionHandler reverseGocodeUsingGoogle(latitude: latitude, longitude: longitude) } func reverseGeocodeLocationUsingGoogleWithCoordinates(coord:CLLocation, onReverseGeocodingCompletionHandler:LMReverseGeocodeCompletionHandler){ reverseGeocodeLocationUsingGoogleWithLatLon(latitude: coord.coordinate.latitude, longitude: coord.coordinate.longitude, onReverseGeocodingCompletionHandler: onReverseGeocodingCompletionHandler) } private func reverseGocodeUsingGoogle(#latitude:Double, longitude: Double){ var urlString = "http://maps.googleapis.com/maps/api/geocode/json?latlng=\(latitude),\(longitude)&sensor=true" as NSString urlString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! performOperationForURL(urlString, type: GeoCodingType.ReverseGeocoding) } private func performOperationForURL(urlString:NSString,type:GeoCodingType){ let url:NSURL? = NSURL(string:urlString as String) let request:NSURLRequest = NSURLRequest(URL:url!) let queue:NSOperationQueue = NSOperationQueue() NSURLConnection.sendAsynchronousRequest(request,queue:queue,completionHandler:{response,data,error in if error != nil { self.setCompletionHandler(responseInfo:nil, placemark:nil, error:error.localizedDescription, type:type) } else { let kStatus = "status" let kOK = "ok" let kZeroResults = "ZERO_RESULTS" let kAPILimit = "OVER_QUERY_LIMIT" let kRequestDenied = "REQUEST_DENIED" let kInvalidRequest = "INVALID_REQUEST" let kInvalidInput = "Invalid Input" let dataAsString: NSString? = NSString(data: data, encoding: NSUTF8StringEncoding) let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary var status = jsonResult.valueForKey(kStatus) as! NSString status = status.lowercaseString if status.isEqualToString(kOK) { let address = AddressParser() address.parseGoogleLocationData(jsonResult) let addressDict = address.getAddressDictionary() let placemark:CLPlacemark = address.getPlacemark() self.setCompletionHandler(responseInfo:addressDict, placemark:placemark, error: nil, type:type) } else if !status.isEqualToString(kZeroResults) && !status.isEqualToString(kAPILimit) && !status.isEqualToString(kRequestDenied) && !status.isEqualToString(kInvalidRequest) { self.setCompletionHandler(responseInfo:nil, placemark:nil, error:kInvalidInput, type:type) } else { //status = (status.componentsSeparatedByString("_") as NSArray).componentsJoinedByString(" ").capitalizedString self.setCompletionHandler(responseInfo:nil, placemark:nil, error:status as String, type:type) } } }) } private func setCompletionHandler(#responseInfo:NSDictionary?,placemark:CLPlacemark?, error:String?,type:GeoCodingType){ if type == GeoCodingType.Geocoding { self.geocodingCompletionHandler!(gecodeInfo:responseInfo,placemark:placemark,error:error) } else { self.reverseGeocodingCompletionHandler!(reverseGecodeInfo:responseInfo,placemark:placemark,error:error) } } } @objc protocol LocationManagerDelegate : NSObjectProtocol { func locationFound(latitude:Double, longitude:Double) optional func locationFoundGetAsString(latitude:NSString, longitude:NSString) optional func locationManagerStatus(status:NSString) optional func locationManagerReceivedError(error:NSString) optional func locationManagerVerboseMessage(message:NSString) } private class AddressParser: NSObject{ private var latitude = NSString() private var longitude = NSString() private var streetNumber = NSString() private var route = NSString() private var locality = NSString() private var subLocality = NSString() private var formattedAddress = NSString() private var administrativeArea = NSString() private var administrativeAreaCode = NSString() private var subAdministrativeArea = NSString() private var postalCode = NSString() private var country = NSString() private var subThoroughfare = NSString() private var thoroughfare = NSString() private var ISOcountryCode = NSString() private var state = NSString() override init() { super.init() } private func getAddressDictionary()-> NSDictionary { var addressDict = NSMutableDictionary() addressDict.setValue(latitude, forKey: "latitude") addressDict.setValue(longitude, forKey: "longitude") addressDict.setValue(streetNumber, forKey: "streetNumber") addressDict.setValue(locality, forKey: "locality") addressDict.setValue(subLocality, forKey: "subLocality") addressDict.setValue(administrativeArea, forKey: "administrativeArea") addressDict.setValue(postalCode, forKey: "postalCode") addressDict.setValue(country, forKey: "country") addressDict.setValue(formattedAddress, forKey: "formattedAddress") return addressDict } private func parseAppleLocationData(placemark:CLPlacemark) { var addressLines = placemark.addressDictionary["FormattedAddressLines"] as! NSArray //self.streetNumber = placemark.subThoroughfare ? placemark.subThoroughfare : "" self.streetNumber = placemark.thoroughfare != nil ? placemark.thoroughfare : "" self.locality = placemark.locality != nil ? placemark.locality : "" self.postalCode = placemark.postalCode != nil ? placemark.postalCode : "" self.subLocality = placemark.subLocality != nil ? placemark.subLocality : "" self.administrativeArea = placemark.administrativeArea != nil ? placemark.administrativeArea : "" self.country = placemark.country != nil ? placemark.country : "" self.longitude = placemark.location.coordinate.longitude.description; self.latitude = placemark.location.coordinate.latitude.description if addressLines.count>0 { self.formattedAddress = addressLines.componentsJoinedByString(", ") } else { self.formattedAddress = "" } } private func parseGoogleLocationData(resultDict:NSDictionary) { let locationDict = (resultDict.valueForKey("results") as! NSArray).firstObject as! NSDictionary let formattedAddrs = locationDict.objectForKey("formatted_address") as! NSString let geometry = locationDict.objectForKey("geometry") as! NSDictionary let location = geometry.objectForKey("location") as! NSDictionary let lat = location.objectForKey("lat") as! Double let lng = location.objectForKey("lng") as! Double self.latitude = lat.description self.longitude = lng.description let addressComponents = locationDict.objectForKey("address_components") as! NSArray self.subThoroughfare = component("street_number", inArray: addressComponents, ofType: "long_name") self.thoroughfare = component("route", inArray: addressComponents, ofType: "long_name") self.streetNumber = self.subThoroughfare self.locality = component("locality", inArray: addressComponents, ofType: "long_name") self.postalCode = component("postal_code", inArray: addressComponents, ofType: "long_name") self.route = component("route", inArray: addressComponents, ofType: "long_name") self.subLocality = component("subLocality", inArray: addressComponents, ofType: "long_name") self.administrativeArea = component("administrative_area_level_1", inArray: addressComponents, ofType: "long_name") self.administrativeAreaCode = component("administrative_area_level_1", inArray: addressComponents, ofType: "short_name") self.subAdministrativeArea = component("administrative_area_level_2", inArray: addressComponents, ofType: "long_name") self.country = component("country", inArray: addressComponents, ofType: "long_name") self.ISOcountryCode = component("country", inArray: addressComponents, ofType: "short_name") self.formattedAddress = formattedAddrs; } private func component(component:NSString,inArray:NSArray,ofType:NSString) -> NSString { let index:NSInteger = inArray.indexOfObjectPassingTest { (obj, idx, stop) -> Bool in var objDict:NSDictionary = obj as! NSDictionary var types:NSArray = objDict.objectForKey("types") as! NSArray let type = types.firstObject as! NSString return type.isEqualToString(component as String) } if index == NSNotFound { return "" } if index >= inArray.count { return "" } var type = ((inArray.objectAtIndex(index) as! NSDictionary).valueForKey(ofType as String)!) as! NSString if type.length > 0 { return type } return "" } private func getPlacemark() -> CLPlacemark { var addressDict = NSMutableDictionary() var formattedAddressArray = self.formattedAddress.componentsSeparatedByString(", ") as Array let kSubAdministrativeArea = "SubAdministrativeArea" let kSubLocality = "SubLocality" let kState = "State" let kStreet = "Street" let kThoroughfare = "Thoroughfare" let kFormattedAddressLines = "FormattedAddressLines" let kSubThoroughfare = "SubThoroughfare" let kPostCodeExtension = "PostCodeExtension" let kCity = "City" let kZIP = "ZIP" let kCountry = "Country" let kCountryCode = "CountryCode" addressDict.setObject(self.subAdministrativeArea, forKey: kSubAdministrativeArea) addressDict.setObject(self.subLocality, forKey: kSubLocality) addressDict.setObject(self.administrativeAreaCode, forKey: kState) addressDict.setObject(formattedAddressArray.first as! NSString, forKey: kStreet) addressDict.setObject(self.thoroughfare, forKey: kThoroughfare) addressDict.setObject(formattedAddressArray, forKey: kFormattedAddressLines) addressDict.setObject(self.subThoroughfare, forKey: kSubThoroughfare) addressDict.setObject("", forKey: kPostCodeExtension) addressDict.setObject(self.locality, forKey: kCity) addressDict.setObject(self.postalCode, forKey: kZIP) addressDict.setObject(self.country, forKey: kCountry) addressDict.setObject(self.ISOcountryCode, forKey: kCountryCode) var lat = self.latitude.doubleValue var lng = self.longitude.doubleValue var coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng) var placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDict as [NSObject : AnyObject]) return (placemark as CLPlacemark) } }
mit
da0d1b292514a7f6db566a711b70eb3d
37.048513
293
0.718123
5.257785
false
false
false
false
Look-ARound/LookARound2
lookaround2/Controllers/PlaceDetail/PlaceDetailCell.swift
1
3107
// // PlaceDetailCell.swift // lookaround2 // // Created by Ali Mir on 11/10/17. // Copyright © 2017 Angela Yu. All rights reserved. // import UIKit import FBSDKCoreKit import FBSDKLoginKit import FBSDKShareKit class PlaceDetailCell: UITableViewCell { @IBOutlet private var nameLabel: UILabel! @IBOutlet private var categoryLabel: UILabel! @IBOutlet private var checkinsCountLabel: UILabel! @IBOutlet private var friendsCountLabel: UILabel! @IBOutlet private var facebookLikeButtonView: UIView! @IBOutlet private var aboutLabel: UILabel! @IBOutlet private var checkInImageView: UIImageView! @IBOutlet private var likeImageView: UIImageView! internal func initCell(with place: Place) { setupViews(with: place) } private func setupViews(with place: Place) { nameLabel.text = place.name checkinsCountLabel.text = "\(place.checkins ?? 0) checkins" categoryLabel.text = place.category aboutLabel.text = place.about setupThemeColors() addLikeControl(objectID: place.id) setupFriendsCountLabel(contextCount: place.contextCount ?? 0) } private func setupFriendsCountLabel(contextCount: Int) { switch contextCount { case 1: friendsCountLabel.text = "\(contextCount) friend likes this" friendsCountLabel.isHidden = false likeImageView.isHidden = false case _ where contextCount > 1: friendsCountLabel.text = "\(contextCount) friends like this" friendsCountLabel.isHidden = false likeImageView.isHidden = false case 0: friendsCountLabel.isHidden = true likeImageView.isHidden = true default: friendsCountLabel.isHidden = true likeImageView.isHidden = true } } private func addLikeControl(objectID: String) { let likeControl = FBSDKLikeControl() likeControl.likeControlStyle = FBSDKLikeControlStyle.standard likeControl.objectType = .openGraph likeControl.frame = facebookLikeButtonView.bounds likeControl.likeControlHorizontalAlignment = .left likeControl.objectID = objectID if facebookLikeButtonView.subviews.count > 0 { let oldView = facebookLikeButtonView.subviews[0] oldView.removeFromSuperview() } facebookLikeButtonView.addSubview(likeControl) } private func setupThemeColors() { categoryLabel.textColor = UIColor.LABrand.detail checkinsCountLabel.textColor = UIColor.LABrand.detail friendsCountLabel.textColor = UIColor.LABrand.standard checkInImageView.tintColor = UIColor.LABrand.detail likeImageView.tintColor = UIColor.LABrand.detail } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
apache-2.0
6574f02a25c1c3e42605b43e179c7c40
32.76087
72
0.674823
5.075163
false
false
false
false
paulomendes/nextel-challange
nextel-challangeTests/MoviesDAO/MoviesDAOTests.swift
1
44618
import XCTest @testable import nextel_challange class MoviesDAOTests: XCTestCase { private static let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter }() override func setUp() { super.setUp() } func testShouldConvertModelCorrectlyNowPlaying() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile,success: @escaping (Data?, PersistenceErrors) -> Void) { success(nil, .invalidCache) return } } class FauxConnector: MoviesConnectorProtocol { func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { let stringResponse = "{\"page\":1,\"results\":[{\"poster_path\":\"/wnVHDbGz7RvDAHFAsVVT88FxhrP.jpg\",\"adult\":false,\"overview\":\"When a wounded Christian Grey tries to entice a cautious Ana Steele back into his life, she demands a new arrangement before she will give him another chance. As the two begin to build trust and find stability, shadowy figures from Christian’s past start to circle the couple, determined to destroy their hopes for a future together.\",\"release_date\":\"2017-02-08\",\"genre_ids\":[18,10749],\"id\":341174,\"original_title\":\"Fifty Shades Darker\",\"original_language\":\"en\",\"title\":\"Fifty Shades Darker\",\"backdrop_path\":\"/rXBB8F6XpHAwci2dihBCcixIHrK.jpg\",\"popularity\":189.509821,\"vote_count\":660,\"video\":false,\"vote_average\":6.3}],\"dates\":{\"maximum\":\"2017-03-02\",\"minimum\":\"2017-01-19\"},\"total_pages\":35,\"total_results\":697}" success(stringResponse.data(using: .utf8)!) } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { //Silience is gold } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.getNowPlayingMovies(success: { (movies) in XCTAssertEqual(movies.count, 1) XCTAssertEqual(movies.first?.posterPath, "/wnVHDbGz7RvDAHFAsVVT88FxhrP.jpg") XCTAssertFalse(movies.first!.adult) XCTAssertEqual(movies.first?.overview, "When a wounded Christian Grey tries to entice a cautious Ana Steele back into his life, she demands a new arrangement before she will give him another chance. As the two begin to build trust and find stability, shadowy figures from Christian’s past start to circle the couple, determined to destroy their hopes for a future together.") XCTAssertEqual(movies.first?.releaseDate, MoviesDAOTests.dateFormatter.date(from: "2017-02-08")) XCTAssertEqual(movies.first?.originalTitle, "Fifty Shades Darker") expec.fulfill() }) { err in XCTFail() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldConvertModelCorrectlyUpcoming() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile,success: @escaping (Data?, PersistenceErrors) -> Void) { success(nil, .invalidCache) return } } class FauxConnector: MoviesConnectorProtocol { func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { let stringResponse = "{\"page\":1,\"results\":[{\"poster_path\":\"/wnVHDbGz7RvDAHFAsVVT88FxhrP.jpg\",\"adult\":false,\"overview\":\"When a wounded Christian Grey tries to entice a cautious Ana Steele back into his life, she demands a new arrangement before she will give him another chance. As the two begin to build trust and find stability, shadowy figures from Christian’s past start to circle the couple, determined to destroy their hopes for a future together.\",\"release_date\":\"2017-02-08\",\"genre_ids\":[18,10749],\"id\":341174,\"original_title\":\"Fifty Shades Darker\",\"original_language\":\"en\",\"title\":\"Fifty Shades Darker\",\"backdrop_path\":\"/rXBB8F6XpHAwci2dihBCcixIHrK.jpg\",\"popularity\":189.509821,\"vote_count\":660,\"video\":false,\"vote_average\":6.3}],\"dates\":{\"maximum\":\"2017-03-02\",\"minimum\":\"2017-01-19\"},\"total_pages\":35,\"total_results\":697}" success(stringResponse.data(using: .utf8)!) } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.getUpcomingMovies(success: { (movies) in XCTAssertEqual(movies.count, 1) XCTAssertEqual(movies.first?.posterPath, "/wnVHDbGz7RvDAHFAsVVT88FxhrP.jpg") XCTAssertFalse(movies.first!.adult) XCTAssertEqual(movies.first?.overview, "When a wounded Christian Grey tries to entice a cautious Ana Steele back into his life, she demands a new arrangement before she will give him another chance. As the two begin to build trust and find stability, shadowy figures from Christian’s past start to circle the couple, determined to destroy their hopes for a future together.") XCTAssertEqual(movies.first?.releaseDate, MoviesDAOTests.dateFormatter.date(from: "2017-02-08")) XCTAssertEqual(movies.first?.originalTitle, "Fifty Shades Darker") expec.fulfill() }) { err in XCTFail() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldConvertModelCorrectlySearch() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile,success: @escaping (Data?, PersistenceErrors) -> Void) { success(nil, .invalidCache) return } } class FauxConnector: MoviesConnectorProtocol { func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { //Silience is gold } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { let stringResponse = "{\"page\":1,\"results\":[{\"poster_path\":\"/wnVHDbGz7RvDAHFAsVVT88FxhrP.jpg\",\"adult\":false,\"overview\":\"When a wounded Christian Grey tries to entice a cautious Ana Steele back into his life, she demands a new arrangement before she will give him another chance. As the two begin to build trust and find stability, shadowy figures from Christian’s past start to circle the couple, determined to destroy their hopes for a future together.\",\"release_date\":\"2017-02-08\",\"genre_ids\":[18,10749],\"id\":341174,\"original_title\":\"Fifty Shades Darker\",\"original_language\":\"en\",\"title\":\"Fifty Shades Darker\",\"backdrop_path\":\"/rXBB8F6XpHAwci2dihBCcixIHrK.jpg\",\"popularity\":189.509821,\"vote_count\":660,\"video\":false,\"vote_average\":6.3}],\"dates\":{\"maximum\":\"2017-03-02\",\"minimum\":\"2017-01-19\"},\"total_pages\":35,\"total_results\":697}" success(stringResponse.data(using: .utf8)!) } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.searchMovieByTitle(query: "query", success: { (movies) in XCTAssertEqual(movies.count, 1) XCTAssertEqual(movies.first?.posterPath, "/wnVHDbGz7RvDAHFAsVVT88FxhrP.jpg") XCTAssertFalse(movies.first!.adult) XCTAssertEqual(movies.first?.overview, "When a wounded Christian Grey tries to entice a cautious Ana Steele back into his life, she demands a new arrangement before she will give him another chance. As the two begin to build trust and find stability, shadowy figures from Christian’s past start to circle the couple, determined to destroy their hopes for a future together.") XCTAssertEqual(movies.first?.releaseDate, MoviesDAOTests.dateFormatter.date(from: "2017-02-08")) XCTAssertEqual(movies.first?.originalTitle, "Fifty Shades Darker") expec.fulfill() }) { err in XCTFail() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldReturnParseErrorForANotConformJsonNowPlaying() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile, success: @escaping (Data?, PersistenceErrors) -> Void) { success(nil, .invalidCache) return } } class FauxConnector: MoviesConnectorProtocol { func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { let stringResponse = "{\"page\":1,\"results\":[{\"postr_path\":\"/wnVHDbGz7RvDAHFAsVVT88FxhrP.jpg\",\"adult\":false,\"overview\":\"When a wounded Christian Grey tries to entice a cautious Ana Steele back into his life, she demands a new arrangement before she will give him another chance. As the two begin to build trust and find stability, shadowy figures from Christian’s past start to circle the couple, determined to destroy their hopes for a future together.\",\"release_date\":\"2017-02-08\",\"genre_ids\":[18,10749],\"id\":341174,\"original_title\":\"Fifty Shades Darker\",\"original_language\":\"en\",\"title\":\"Fifty Shades Darker\",\"backdrop_path\":\"/rXBB8F6XpHAwci2dihBCcixIHrK.jpg\",\"popularity\":189.509821,\"vote_count\":660,\"video\":false,\"vote_average\":6.3}],\"dates\":{\"maximum\":\"2017-03-02\",\"minimum\":\"2017-01-19\"},\"total_pages\":35,\"total_results\":697}" success(stringResponse.data(using: .utf8)!) } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { //Silience is gold } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.getNowPlayingMovies(success: { (movies) in XCTFail() expec.fulfill() }) { err in XCTAssertEqual(err, .parserError) expec.fulfill() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldReturnParseErrorForANotConformJsonUpcoming() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile, success: @escaping (Data?, PersistenceErrors) -> Void) { success(nil, .invalidCache) return } } class FauxConnector: MoviesConnectorProtocol { func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { let stringResponse = "{\"page\":1,\"results\":[{\"postr_path\":\"/wnVHDbGz7RvDAHFAsVVT88FxhrP.jpg\",\"adult\":false,\"overview\":\"When a wounded Christian Grey tries to entice a cautious Ana Steele back into his life, she demands a new arrangement before she will give him another chance. As the two begin to build trust and find stability, shadowy figures from Christian’s past start to circle the couple, determined to destroy their hopes for a future together.\",\"release_date\":\"2017-02-08\",\"genre_ids\":[18,10749],\"id\":341174,\"original_title\":\"Fifty Shades Darker\",\"original_language\":\"en\",\"title\":\"Fifty Shades Darker\",\"backdrop_path\":\"/rXBB8F6XpHAwci2dihBCcixIHrK.jpg\",\"popularity\":189.509821,\"vote_count\":660,\"video\":false,\"vote_average\":6.3}],\"dates\":{\"maximum\":\"2017-03-02\",\"minimum\":\"2017-01-19\"},\"total_pages\":35,\"total_results\":697}" success(stringResponse.data(using: .utf8)!) } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.getUpcomingMovies(success: { (movies) in XCTFail() expec.fulfill() }) { err in XCTAssertEqual(err, .parserError) expec.fulfill() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldReturnEmptyArrayForANotConformJsonSearch() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile, success: @escaping (Data?, PersistenceErrors) -> Void) { success(nil, .invalidCache) return } } class FauxConnector: MoviesConnectorProtocol { func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { //Silience is gold } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { let stringResponse = "{\"page\":1,\"results\":[{\"postr_path\":\"/wnVHDbGz7RvDAHFAsVVT88FxhrP.jpg\",\"adult\":false,\"overview\":\"When a wounded Christian Grey tries to entice a cautious Ana Steele back into his life, she demands a new arrangement before she will give him another chance. As the two begin to build trust and find stability, shadowy figures from Christian’s past start to circle the couple, determined to destroy their hopes for a future together.\",\"release_date\":\"2017-02-08\",\"genre_ids\":[18,10749],\"id\":341174,\"original_title\":\"Fifty Shades Darker\",\"original_language\":\"en\",\"title\":\"Fifty Shades Darker\",\"backdrop_path\":\"/rXBB8F6XpHAwci2dihBCcixIHrK.jpg\",\"popularity\":189.509821,\"vote_count\":660,\"video\":false,\"vote_average\":6.3}],\"dates\":{\"maximum\":\"2017-03-02\",\"minimum\":\"2017-01-19\"},\"total_pages\":35,\"total_results\":697}" success(stringResponse.data(using: .utf8)!) } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.searchMovieByTitle(query: "query", success: { (movies) in XCTAssertEqual(movies.count, 0) expec.fulfill() }) { err in XCTFail() expec.fulfill() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldReturnInternetErrorInCaseOfInternetErrorOnConnectorNowPlaying() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile, success: @escaping (Data?, PersistenceErrors) -> Void) { success(nil, .invalidCache) return } } class FauxConnector: MoviesConnectorProtocol { func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { failure(.internetError) } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { //Silience is gold } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.getNowPlayingMovies(success: { (movies) in XCTFail() expec.fulfill() }) { err in XCTAssertEqual(err, .connectionError) expec.fulfill() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldReturnInternetErrorInCaseOfInternetErrorOnConnectorUpcoming() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile, success: @escaping (Data?, PersistenceErrors) -> Void) { success(nil, .invalidCache) return } } class FauxConnector: MoviesConnectorProtocol { func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { failure(.internetError) } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.getUpcomingMovies(success: { (movies) in XCTFail() expec.fulfill() }) { err in XCTAssertEqual(err, .connectionError) expec.fulfill() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldReturnInternetErrorInCaseOfInternetErrorOnConnectorSearch() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile, success: @escaping (Data?, PersistenceErrors) -> Void) { success(nil, .invalidCache) return } } class FauxConnector: MoviesConnectorProtocol { func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { //Silience is gold } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { failure(.internetError) } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.searchMovieByTitle(query: "query", success: { (movies) in XCTFail() expec.fulfill() }) { err in XCTAssertEqual(err, .connectionError) expec.fulfill() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldReturnFileErrorInCaseConnectorReturnAFileErrorNowPlaying() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile, success: @escaping (Data?, PersistenceErrors) -> Void) { success(nil, .invalidCache) return } } class FauxConnector: MoviesConnectorProtocol { func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { failure(.errorInSaveLocalFile) } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { //Silience is gold } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.getNowPlayingMovies(success: { (movies) in XCTFail() expec.fulfill() }) { err in XCTAssertEqual(err, .fileError) expec.fulfill() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldReturnFileErrorInCaseConnectorReturnAFileErrorUpcoming() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile, success: @escaping (Data?, PersistenceErrors) -> Void) { success(nil, .invalidCache) return } } class FauxConnector: MoviesConnectorProtocol { func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { failure(.errorInSaveLocalFile) } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.getUpcomingMovies(success: { (movies) in XCTFail() expec.fulfill() }) { err in XCTAssertEqual(err, .fileError) expec.fulfill() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldCallWebServiceInCaseOfFileNotFoundNowPlaying() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile, success: @escaping (Data?, PersistenceErrors) -> Void) { success(nil, .fileNotFound) return } } class FauxConnector: MoviesConnectorProtocol { var passed = false func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { self.passed = true failure(.internetError) } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { //Silience is gold } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.getNowPlayingMovies(success: { (movies) in XCTFail() expec.fulfill() }) { err in XCTAssertTrue(connector.passed) expec.fulfill() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldCallWebServiceInCaseOfFileNotFoundUpcomming() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile, success: @escaping (Data?, PersistenceErrors) -> Void) { success(nil, .fileNotFound) return } } class FauxConnector: MoviesConnectorProtocol { var passed = false func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { self.passed = true failure(.internetError) } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.getUpcomingMovies(success: { (movies) in XCTFail() expec.fulfill() }) { err in XCTAssertTrue(connector.passed) expec.fulfill() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldCallWebServiceInCaseOfInvalidFileFormatNowPlaying() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile, success: @escaping (Data?, PersistenceErrors) -> Void) { success(nil, .invalidFileFormat) return } } class FauxConnector: MoviesConnectorProtocol { var passed = false func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { self.passed = true failure(.internetError) } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { //Silience is gold } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.getNowPlayingMovies(success: { (movies) in XCTFail() expec.fulfill() }) { err in XCTAssertTrue(connector.passed) expec.fulfill() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldCallWebServiceInCaseOfInvalidFileFormatNowUpcomming() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile, success: @escaping (Data?, PersistenceErrors) -> Void) { success(nil, .invalidFileFormat) return } } class FauxConnector: MoviesConnectorProtocol { var passed = false func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is Golden } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { self.passed = true failure(.internetError) } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is Gloden } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.getUpcomingMovies(success: { (movies) in XCTFail() expec.fulfill() }) { err in XCTAssertTrue(connector.passed) expec.fulfill() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldCallWebServiceInCaseOfInvalidFileFormatSearch() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile, success: @escaping (Data?, PersistenceErrors) -> Void) { success(nil, .invalidFileFormat) return } } class FauxConnector: MoviesConnectorProtocol { var passed = false func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is Golden } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { //Silience is Golden } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { self.passed = true failure(.internetError) } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.searchMovieByTitle(query: "query", success: { (movies) in XCTFail() expec.fulfill() }) { err in XCTAssertTrue(connector.passed) expec.fulfill() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldConvertCorrectlyLocalFileDiskNowPlaying() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile, success: @escaping (Data?, PersistenceErrors) -> Void) { let stringResponse = "{\"page\":1,\"results\":[{\"poster_path\":\"/wnVHDbGz7RvDAHFAsVVT88FxhrP.jpg\",\"adult\":false,\"overview\":\"When a wounded Christian Grey tries to entice a cautious Ana Steele back into his life, she demands a new arrangement before she will give him another chance. As the two begin to build trust and find stability, shadowy figures from Christian’s past start to circle the couple, determined to destroy their hopes for a future together.\",\"release_date\":\"2017-02-08\",\"genre_ids\":[18,10749],\"id\":341174,\"original_title\":\"Fifty Shades Darker\",\"original_language\":\"en\",\"title\":\"Fifty Shades Darker\",\"backdrop_path\":\"/rXBB8F6XpHAwci2dihBCcixIHrK.jpg\",\"popularity\":189.509821,\"vote_count\":660,\"video\":false,\"vote_average\":6.3}],\"dates\":{\"maximum\":\"2017-03-02\",\"minimum\":\"2017-01-19\"},\"total_pages\":35,\"total_results\":697}" success(stringResponse.data(using: .utf8)!, .none) } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { //Silience is gold } } class FauxConnector: MoviesConnectorProtocol { var passed = false func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { self.passed = true failure(.internetError) } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { //Silience is gold } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.getNowPlayingMovies(success: { (movies) in XCTAssertEqual(movies.count, 1) XCTAssertEqual(movies.first?.posterPath, "/wnVHDbGz7RvDAHFAsVVT88FxhrP.jpg") XCTAssertFalse(movies.first!.adult) XCTAssertEqual(movies.first?.overview, "When a wounded Christian Grey tries to entice a cautious Ana Steele back into his life, she demands a new arrangement before she will give him another chance. As the two begin to build trust and find stability, shadowy figures from Christian’s past start to circle the couple, determined to destroy their hopes for a future together.") XCTAssertEqual(movies.first?.releaseDate, MoviesDAOTests.dateFormatter.date(from: "2017-02-08")) XCTAssertEqual(movies.first?.originalTitle, "Fifty Shades Darker") expec.fulfill() }) { err in XCTFail() XCTAssertTrue(connector.passed) expec.fulfill() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } func testShouldConvertCorrectlyLocalFileDiskUpcoming() { class FauxMoviesPersistence: Persistence { func saveFile(stringJson: String, file: MovieFile) -> Bool { return true } func readFile(file: MovieFile, success: @escaping (Data?, PersistenceErrors) -> Void) { let stringResponse = "{\"page\":1,\"results\":[{\"poster_path\":\"/wnVHDbGz7RvDAHFAsVVT88FxhrP.jpg\",\"adult\":false,\"overview\":\"When a wounded Christian Grey tries to entice a cautious Ana Steele back into his life, she demands a new arrangement before she will give him another chance. As the two begin to build trust and find stability, shadowy figures from Christian’s past start to circle the couple, determined to destroy their hopes for a future together.\",\"release_date\":\"2017-02-08\",\"genre_ids\":[18,10749],\"id\":341174,\"original_title\":\"Fifty Shades Darker\",\"original_language\":\"en\",\"title\":\"Fifty Shades Darker\",\"backdrop_path\":\"/rXBB8F6XpHAwci2dihBCcixIHrK.jpg\",\"popularity\":189.509821,\"vote_count\":660,\"video\":false,\"vote_average\":6.3}],\"dates\":{\"maximum\":\"2017-03-02\",\"minimum\":\"2017-01-19\"},\"total_pages\":35,\"total_results\":697}" success(stringResponse.data(using: .utf8)!, .none) } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { //Silience is gold } } class FauxConnector: MoviesConnectorProtocol { var passed = false func getNowPlayingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { self.passed = true failure(.internetError) } func getUpcomingMovies(success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void) { //Silience is gold } func searchMovieByOriginalTitle(query: String, success: @escaping (Data) -> Void, failure: @escaping (MoviesConnectorError) -> Void ) { //Silience is gold } } let moviesPersistence = FauxMoviesPersistence() let connector = FauxConnector() let moviesDAO = MoviesDAO(moviesPersistence: moviesPersistence, connector: connector) let expec = expectation(description: "NowPlayingMovies") moviesDAO.getUpcomingMovies(success: { (movies) in XCTAssertEqual(movies.count, 1) XCTAssertEqual(movies.first?.posterPath, "/wnVHDbGz7RvDAHFAsVVT88FxhrP.jpg") XCTAssertFalse(movies.first!.adult) XCTAssertEqual(movies.first?.overview, "When a wounded Christian Grey tries to entice a cautious Ana Steele back into his life, she demands a new arrangement before she will give him another chance. As the two begin to build trust and find stability, shadowy figures from Christian’s past start to circle the couple, determined to destroy their hopes for a future together.") XCTAssertEqual(movies.first?.releaseDate, MoviesDAOTests.dateFormatter.date(from: "2017-02-08")) XCTAssertEqual(movies.first?.originalTitle, "Fifty Shades Darker") expec.fulfill() }) { err in XCTFail() XCTAssertTrue(connector.passed) expec.fulfill() } self.waitForExpectations(timeout: 5) { (err) in XCTAssertNil(err, "Something gone wrong") } } }
mit
124b8631690bc4a05774c8f5bdc745a2
48.327434
908
0.579229
4.992946
false
false
false
false
giftbott/ViperModuleTemplate
ViperModule.xctemplate/Basic/___FILEBASENAME___Wireframe.swift
1
923
// // ___FILENAME___ // ___PROJECTNAME___ // // Created ___FULLUSERNAME___ on ___DATE___. // Copyright © ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved. // import UIKit protocol ___VARIABLE_viperModuleName___WireframeProtocol: class { // Presenter -> Wireframe } // MARK: - Class Implementation final class ___VARIABLE_viperModuleName___Wireframe: ___VARIABLE_viperModuleName___WireframeProtocol { weak var view: UIViewController! // MARK: Initializing static func createModule() -> ___VARIABLE_viperModuleName___ViewController { let view = ___VARIABLE_viperModuleName___ViewController() let wireframe = ___VARIABLE_viperModuleName___Wireframe() let presenter = ___VARIABLE_viperModuleName___Presenter() view.presenter = presenter wireframe.view = view presenter.view = view presenter.wireframe = wireframe return view } // MARK: Navigation }
mit
1c98d66b555f4821eb0046fa8a580b91
23.918919
102
0.670282
4.519608
false
false
false
false
kingka/SwiftWeiBo
SwiftWeiBo/SwiftWeiBo/Classes/Compose/EmoticonController/UITextView+Category.swift
1
3203
// // UITextView+Category.swift // Emoticon // // Created by Imanol on 5/21/16. // Copyright © 2016 Imanol. All rights reserved. // import UIKit extension UITextView { func insertEmoticons(emoticon : Emoticon){ //判断当前点击的是否是emoji表情 if emoticon.emojiStr != nil { replaceRange(selectedTextRange!, withText: emoticon.emojiStr!) // 判断当前点击的是否是表情图片 }else if emoticon.png != nil { let imgText = EmoticonTextAttachment.createImageText(emoticon, font: font ?? UIFont.systemFontOfSize(15)) //拿到textView content let textViewStr = NSMutableAttributedString(attributedString: attributedText) //insert emoticon to curse location let range = selectedRange textViewStr.replaceCharactersInRange(range, withAttributedString: imgText) //因为创建的字符串有自己默认的size ,所以需要改变,这里的NSMakeRange(range.location, 1),之所以是1,是因为上面已经insert了表情进来,这里要改变字体,是因为如果前一个inser了图片,接着insert emoji 表情,如果不改字体大小,emoji表情的大小会不正确 textViewStr.addAttribute(NSFontAttributeName, value: font ?? UIFont.systemFontOfSize(15), range: NSMakeRange(range.location, 1)) //替换 textView content attributedText = textViewStr //恢复光标位置 // 两个参数: 第一个是指定光标所在的位置, 第二个参数是选中文本的个数 selectedRange = NSMakeRange(range.location + 1, 0) } //删除按钮 if emoticon.isDeleteBtn{ deleteBackward() } // 自己主动促发textViewDidChange方法,如果有placeholder,点击表情不会消失那些提示,所以需要主动触发 delegate?.textViewDidChange!(self) } func emoticonStr()->String{ var str = String() //转成发送给服务器的str attributedText.enumerateAttributesInRange(NSMakeRange(0, attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (objc, range, _) -> Void in /* // 遍历的时候传递给我们的objc是一个字典, 如果字典中的NSAttachment这个key有值 // 那么就证明当前是一个图片 print(objc["NSAttachment"]) // range就是纯字符串的范围 // 如果纯字符串中间有图片表情, 那么range就会传递多次 print(range) let res = (self.customTextView.text as NSString).substringWithRange(range) print(res) print("++++++++++++++++++++++++++") */ if objc["NSAttachment"] != nil { let attatchment = objc["NSAttachment"] as! EmoticonTextAttachment str += attatchment.chs! }else{ str += (self.text as NSString).substringWithRange(range) } } return str } }
mit
fa0cc56fff57abae523194058369a0ef
34.6
178
0.594757
4.611399
false
false
false
false
hejunbinlan/Operations
Operations/Conditions/BlockCondition.swift
1
1112
// // BlockCondition.swift // Operations // // Created by Daniel Thorpe on 22/07/2015. // Copyright (c) 2015 Daniel Thorpe. All rights reserved. // import Foundation /** An `OperationCondition` which will be satisfied if the block returns true. */ public struct BlockCondition: OperationCondition { public typealias ConditionBlockType = () -> Bool public enum Error: ErrorType { case BlockConditionFailed } public let name = "Block Condition" public let isMutuallyExclusive = false let condition: ConditionBlockType public init(block: ConditionBlockType) { condition = block } public func dependencyForOperation(operation: Operation) -> NSOperation? { return .None } public func evaluateForOperation(operation: Operation, completion: OperationConditionResult -> Void) { completion(condition() ? .Satisfied : .Failed(Error.BlockConditionFailed)) } } extension BlockCondition.Error: Equatable { } public func ==(a: BlockCondition.Error, b: BlockCondition.Error) -> Bool { return true // Only one case in the enum }
mit
9a29af77ab68034b36375779262f70b0
24.272727
106
0.704137
4.672269
false
false
false
false
beallej/krlx-app
KRLX/KRLX/VolumeViewController.swift
1
1328
// // VolumeViewController.swift // KRLX // // This file handles volume control functionality located on the live stream view. // // Created by Josie Bealle, Phuong Dinh, Maraki Ketema, Naomi Yamamoto on 5/30/15. // Copyright (c) 2015 KRLXpert. All rights reserved. // import Foundation class VolumeViewController: UIViewController { var appDelegate: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate //Make vertical slider //Reference: http://stackoverflow.com/questions/29731891/how-can-i-make-a-vertical-slider-in-swift @IBOutlet weak var volumeSlider: UISlider!{ didSet{ volumeSlider.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_2)) } } override func viewDidLoad() { volumeSlider.value = appDelegate.currentVolume super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func changeVolume(sender: UISlider) { self.appDelegate.currentVolume = Float(sender.value) self.appDelegate.player.volume = appDelegate.currentVolume } }
mit
74caf49ac0cac958be7bb13fb6c5434b
28.533333
102
0.677711
4.627178
false
false
false
false
Jackysonglanlan/Scripts
swift/xunyou_accelerator/Sources/srcLibs/SwifterSwift/Foundation/URLExtensions.swift
1
5314
// // URLExtensions.swift // SwifterSwift // // Created by Omar Albeik on 03/02/2017. // Copyright © 2017 SwifterSwift // #if canImport(Foundation) import Foundation #if canImport(UIKit) && canImport(AVFoundation) import UIKit import AVFoundation #endif // MARK: - Properties public extension URL { /// SwifterSwift: Dictionary of the URL's query parameters public var queryParameters: [String: String]? { guard let components = URLComponents(url: self, resolvingAgainstBaseURL: false), let queryItems = components.queryItems else { return nil } var items: [String: String] = [:] for queryItem in queryItems { items[queryItem.name] = queryItem.value } return items } } // MARK: - Methods public extension URL { /// SwifterSwift: URL with appending query parameters. /// /// let url = URL(string: "https://google.com")! /// let param = ["q": "Swifter Swift"] /// url.appendingQueryParameters(params) -> "https://google.com?q=Swifter%20Swift" /// /// - Parameter parameters: parameters dictionary. /// - Returns: URL with appending given query parameters. public func appendingQueryParameters(_ parameters: [String: String]) -> URL { var urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: true)! var items = urlComponents.queryItems ?? [] items += parameters.map({ URLQueryItem(name: $0, value: $1) }) urlComponents.queryItems = items return urlComponents.url! } /// SwifterSwift: Append query parameters to URL. /// /// var url = URL(string: "https://google.com")! /// let param = ["q": "Swifter Swift"] /// url.appendQueryParameters(params) /// print(url) // prints "https://google.com?q=Swifter%20Swift" /// /// - Parameter parameters: parameters dictionary. public mutating func appendQueryParameters(_ parameters: [String: String]) { self = appendingQueryParameters(parameters) } /// SwifterSwift: Get value of a query key. /// /// var url = URL(string: "https://google.com?code=12345")! /// queryValue(for: "code") -> "12345" /// /// - Parameter key: The key of a query value. public func queryValue(for key: String) -> String? { let stringURL = self.absoluteString guard let items = URLComponents(string: stringURL)?.queryItems else { return nil } for item in items where item.name == key { return item.value } return nil } /// SwifterSwift: Returns a new URL by removing all the path components. /// /// let url = URL(string: "https://domain.com/path/other")! /// print(url.deletingAllPathComponents()) // prints "https://domain.com/" /// /// - Returns: URL with all path components removed. public func deletingAllPathComponents() -> URL { var url: URL = self for _ in 0..<pathComponents.count - 1 { url.deleteLastPathComponent() } return url } /// SwifterSwift: Remove all the path components from the URL. /// /// var url = URL(string: "https://domain.com/path/other")! /// url.deleteAllPathComponents() /// print(url) // prints "https://domain.com/" public mutating func deleteAllPathComponents() { for _ in 0..<pathComponents.count - 1 { deleteLastPathComponent() } } /// SwifterSwift: Generates new URL that does not have scheme. /// /// let url = URL(string: "https://domain.com")! /// print(url.droppedScheme()) // prints "domain.com" public func droppedScheme() -> URL? { if let scheme = self.scheme { let droppedScheme = String(self.absoluteString.dropFirst(scheme.count + 3)) return URL(string: droppedScheme) } guard host != nil else { return self } let droppedScheme = String(absoluteString.dropFirst(2)) return URL(string: droppedScheme) } } // MARK: - Methods public extension URL { #if os(iOS) || os(tvOS) /// Generate a thumbnail image from given url. Returns nil if no thumbnail could be created. This function may take some time to complete. It's recommended to dispatch the call if the thumbnail is not generated from a local resource. /// /// var url = URL(string: "https://video.golem.de/files/1/1/20637/wrkw0718-sd.mp4")! /// var thumbnail = url.thumbnail() /// thumbnail = url.thumbnail(fromTime: 5) /// /// DisptachQueue.main.async { /// someImageView.image = url.thumbnail() /// } /// /// - Parameter time: Seconds into the video where the image should be generated. /// - Returns: The UIImage result of the AVAssetImageGenerator public func thumbnail(fromTime time: Float64 = 0) -> UIImage? { let imageGenerator = AVAssetImageGenerator(asset: AVAsset(url: self)) let time = CMTimeMakeWithSeconds(time, preferredTimescale: 1) var actualTime = CMTimeMake(value: 0, timescale: 0) guard let cgImage = try? imageGenerator.copyCGImage(at: time, actualTime: &actualTime) else { return nil } return UIImage(cgImage: cgImage) } #endif } #endif
unlicense
c8bfb7f5af433c2367c71721abc7915e
33.72549
237
0.623377
4.340686
false
false
false
false
crescentflare/SmartMockServer
MockLibIOS/SmartMockLib/Classes/utility/SmartMockFileUtility.swift
1
4690
// // SmartMockFileUtility.swift // SmartMockServer Pod // // Main library utility: easily access files with file:/// or bundle:/// or document:/// // import CommonCrypto class SmartMockFileUtility { // -- // MARK: Initialization // -- private init() { // Private constructor, only static methods allowed } // -- // MARK: Utility functions // -- static func list(fromPath: String) -> [String]? { if let fileList = try? FileManager.default.contentsOfDirectory(atPath: getRawPath(fromPath)) { var filteredList: [String] = [] for fileItem in fileList { if fileItem.lowercased() != "thumbs.db" && fileItem.lowercased() != ".ds_store" { filteredList.append(fileItem) } } return filteredList } return nil } static func recursiveList(fromPath: String) -> [String]? { if let items = list(fromPath: fromPath) { var files: [String] = [] for item in items { let isFile = SmartMockFileUtility.getLength(ofPath: fromPath + "/" + item) > 0 if !isFile { if let dirFiles = recursiveList(fromPath: fromPath + "/" + item) { for dirFile in dirFiles { files.append(item + "/" + dirFile) } } } else { files.append(item) } } return files } return nil } static func open(path: String) -> InputStream? { if let inputStream = InputStream(fileAtPath: getRawPath(path)) { inputStream.open() return inputStream } return nil } static func getLength(ofPath: String) -> Int { if let attr = try? FileManager.default.attributesOfItem(atPath: getRawPath(ofPath)) { if let fileType = attr[FileAttributeKey.type] { if fileType as? String == FileAttributeType.typeDirectory.rawValue { return 0 } } if let fileSize = attr[FileAttributeKey.size] { return (fileSize as! NSNumber).intValue } return 0 } return -1 } static func exists(path: String) -> Bool { if let _ = try? FileManager.default.attributesOfItem(atPath: getRawPath(path)) { return true } return false } static func readFromInputStream(_ stream: InputStream) -> String { let data = NSMutableData() var buffer = [UInt8](repeating: 0, count: 4096) while stream.hasBytesAvailable { let bytesRead = stream.read(&buffer, maxLength: buffer.count) data.append(buffer, length: bytesRead) } let result = String(data: data as Data, encoding: String.Encoding.utf8) ?? "" stream.close() return result } static func obtainSHA256(path: String) -> String { if let inputStream = open(path: path) { // Read stream into data let inputData = NSMutableData() var buffer = [UInt8](repeating: 0, count: 4096) while inputStream.hasBytesAvailable { let bytesRead = inputStream.read(&buffer, maxLength: buffer.count) inputData.append(buffer, length: bytesRead) } inputStream.close() // Obtain the SHA256 hash let data = inputData as Data let hash = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) -> [UInt8] in var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH)) CC_SHA256(bytes.baseAddress, CC_LONG(data.count), &hash) return hash } // Return SHA256 hash string formatted as hexadecimal return hash.map { String(format: "%02hhx", $0) }.joined() } return "" } static func getRawPath(_ path: String) -> String { if path.hasPrefix("bundle:///") { return (Bundle.main.resourcePath ?? "") + "/" + path.replacingOccurrences(of: "bundle:///", with: "") } else if path.hasPrefix("document:///") { let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let documentPath = paths[0] return documentPath + "/" + path.replacingOccurrences(of: "document:///", with: "") } return path.replacingOccurrences(of: "file:///", with: "/") } }
mit
2a64aeeaa01902142f2695bb1406a824
33.485294
113
0.5371
4.890511
false
false
false
false
jadevance/fuzz-therapy-iOS
Fuzz Therapy/CreateOrEditProfileViewController.swift
1
9283
// // CreateOrEditProfileViewController.swift // Fuzz Therapy // // Created by Jade Vance on 8/11/16. // Copyright © 2016 Jade Vance. All rights reserved. // import Foundation import Alamofire import SwiftyJSON import RealmSwift import UIKit // Match the ObjC symbol name inside Main.storyboard. @objc(CreateOrEditViewController) class CreateOrEditViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var nameField: UITextField! @IBOutlet weak var locationField: UITextField! @IBOutlet weak var availabilityField: UITextField! @IBOutlet weak var dogNameField: UITextField! @IBOutlet weak var dogBreedField: UITextField! @IBOutlet weak var dogAgeField: UITextField! @IBOutlet weak var imagePicked: UIImageView! @IBOutlet weak var addPhoto: UIButton! @IBOutlet weak var photoLibrary: UIButton! @IBOutlet weak var saveProfile: UIButton! @IBOutlet weak var cancel: UIButton! let imagePicker: UIImagePickerController! = UIImagePickerController() override func viewDidLoad() { super.viewDidLoad() saveProfile.enabled = false // this is so gross but idk self.addPhoto.layer.cornerRadius = 5.0; self.addPhoto.layer.borderColor = UIColor.blackColor().CGColor self.addPhoto.layer.borderWidth = 1.0 self.addPhoto.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5) self.photoLibrary.layer.cornerRadius = 5.0; self.photoLibrary.layer.borderColor = UIColor.blackColor().CGColor self.photoLibrary.layer.borderWidth = 1.0 self.photoLibrary.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5) self.saveProfile.layer.cornerRadius = 5.0; self.saveProfile.tintColor = UIColor.lightGrayColor() self.saveProfile.layer.borderColor = UIColor.lightGrayColor().CGColor self.saveProfile.layer.borderWidth = 1.0 self.saveProfile.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5) self.cancel.layer.cornerRadius = 5.0; self.cancel.layer.borderColor = UIColor.blackColor().CGColor self.cancel.layer.borderWidth = 1.0 self.cancel.contentEdgeInsets = UIEdgeInsetsMake(5,5,5,5) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func onTextFieldEditingChanged(sender: AnyObject) { let input1 = checkTextInput(nameField.text!) let input2 = checkTextInput(locationField.text!) let input3 = checkTextInput(availabilityField.text!) let input4 = checkTextInput(dogNameField.text!) let input5 = checkTextInput(dogBreedField.text!) let input6 = checkTextInput(dogAgeField.text!) if (input1 && input2 && input3 && input4 && input5 && input6) == true { // true saveProfile.enabled = true self.saveProfile.layer.borderColor = UIColor(red: 0, green: 0.7373, blue: 0.0118, alpha: 1.0).CGColor self.saveProfile.tintColor = UIColor(red: 0, green: 0.7373, blue: 0.0118, alpha: 1.0) self.saveProfile.setTitleColor(UIColor(red: 0, green: 0.7373, blue: 0.0118, alpha: 1.0), forState: .Normal) self.saveProfile.backgroundColor = UIColor(red: 0.7333, green: 0.9765, blue: 0.7373, alpha: 1.0) } else { // false saveProfile.enabled = false self.saveProfile.tintColor = UIColor.lightGrayColor() self.saveProfile.layer.borderColor = UIColor.lightGrayColor().CGColor self.saveProfile.setTitleColor(UIColor.lightGrayColor(), forState: .Normal) self.saveProfile.backgroundColor = UIColor(red: 0 , green: 0, blue: 0, alpha: 0) } } func checkTextInput(text: String) -> Bool { var result = false if text != "" { result = true } return result } @IBAction func onTextFieldDoneEditing(sender: UITextField) { sender.resignFirstResponder() } @IBAction func onTapGestureRecognized(sender: AnyObject) { nameField.resignFirstResponder() locationField.resignFirstResponder() availabilityField.resignFirstResponder() dogNameField.resignFirstResponder() dogBreedField.resignFirstResponder() dogAgeField.resignFirstResponder() } @IBAction func onCameraButtonPressed(sender: UIButton) { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.Camera; imagePicker.allowsEditing = true self.presentViewController(imagePicker, animated: true, completion: nil) } } @IBAction func onPhotoLibraryPressed(sender: AnyObject) { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) { let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary; imagePicker.allowsEditing = true self.presentViewController(imagePicker, animated: true, completion: nil) } } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) { imagePicked.image = image self.dismissViewControllerAnimated(true, completion: {}); } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: {}) } @IBAction func onCancelButtonPressed(sender: AnyObject) { let alert = UIAlertController(title: "Action Cancelled!", message: "Profile not saved", preferredStyle: .Alert) let OKAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (_)in self.performSegueWithIdentifier("unwindToMenu", sender: self) }) alert.addAction(OKAction) self.presentViewController(alert, animated: true, completion: nil) } @IBAction func onSaveButtonPressed(sender: AnyObject) { let alert = UIAlertController(title: "Success!", message: "Profile Saved!!", preferredStyle: .Alert) let OKAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (_)in self.performSegueWithIdentifier("ShowResults", sender: self) }) alert.addAction(OKAction) self.presentViewController(alert, animated: true, completion: nil) // compresses and encodes image data into NSData let imageData = UIImageJPEGRepresentation(imagePicked.image!, 0.6) let compressedJPGImage = UIImage(data: imageData!) UIImageWriteToSavedPhotosAlbum(compressedJPGImage!, nil, nil, nil) // make an api call to create new account / save details locally in a singleton let gUserId = GoogleUser.sharedInstance.user!.userId let name = nameField.text! let location = locationField.text! let availability = availabilityField.text! let dogName = dogNameField.text! let dogBreed = dogBreedField.text! let dogAge:Int? = Int(dogAgeField.text!) let email = GoogleUser.sharedInstance.user!.email let parameters = [ "uid": "\(gUserId)", "name": "\(name)", "location": "\(location)", "availability": "\(availability)", "dog_name": "\(dogName)", "dog_breed": "\(dogBreed)", "dog_age": "\(dogAge)", "email": "\(email)" ] let myUser = User(name:name, uid:gUserId, location:location, availability:availability, dogName:dogName, dogBreed:dogBreed, dogAge:dogAge!, email:email) CurrentUser.sharedInstance.user = myUser getSearchResults() { searchResults in } // send the text data Alamofire.request(.POST, "http://localhost:3000/api/create/", parameters: parameters) .responseJSON { response in } // send the image data Alamofire.upload(.POST, "http://localhost:3000/api/photo/", multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(data: "\(gUserId)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"uid") multipartFormData.appendBodyPart(data: imageData!, name: "dog_picture", fileName:"DOG.jpg", mimeType: "image/jpeg") }, encodingCompletion: { result in switch result { case .Success(let upload, _, _): upload.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in } upload.responseString { response in } case .Failure: break } } ) } }
apache-2.0
a8aab0a97493efb0403b37175fb07ffa
41.774194
160
0.647167
5.074904
false
false
false
false
SASAbus/SASAbus-ios
SASAbus/Data/Model/BBusStop.swift
1
1787
import RealmSwift import ObjectMapper class BBusStop: Mappable { var id = 0 var family = 0 var nameDe: String = "" var nameIt: String = "" var municDe: String = "" var municIt: String = "" var lat: Float = 0.0 var lng: Float = 0.0 required convenience init?(map: Map) { self.init() } convenience init(id: Int, name: String, munic: String, lat: Float, lng: Float, family: Int) { self.init() self.id = id self.family = family nameDe = name nameIt = name municDe = munic municIt = munic self.lat = lat self.lng = lng } convenience init(fromRealm: BusStop) { self.init() self.id = fromRealm.id self.family = fromRealm.family self.nameDe = fromRealm.nameDe! self.nameIt = fromRealm.nameIt! self.municDe = fromRealm.municDe! self.municIt = fromRealm.municIt! self.lat = fromRealm.lat self.lng = fromRealm.lng } func name(locale: String = Locales.get()) -> String { return locale == "de" ? nameDe : nameIt } func munic(locale: String = Locales.get()) -> String { return locale == "de" ? municDe : municIt } func mapping(map: Map) { id <- map["id"] family <- map["family"] nameDe <- map["nameDe"] nameIt <- map["nameIt"] municDe <- map["municDe"] municIt <- map["municIt"] lat <- map["lat"] lng <- map["lng"] } } extension BBusStop: Hashable { var hashValue: Int { return family } public static func ==(lhs: BBusStop, rhs: BBusStop) -> Bool { return lhs.family == rhs.family } }
gpl-3.0
79e65a53892e4513788610c437db6904
20.023529
97
0.529938
3.746331
false
false
false
false
zSher/BulletThief
BulletThief/BulletThief/Enemy.swift
1
3057
// // Enemy.swift // BulletThief // // Created by Zachary on 5/6/15. // Copyright (c) 2015 Zachary. All rights reserved. // import Foundation import SpriteKit class Enemy: SKSpriteNode { var gun:Gun! var movementPath:UIBezierPath? var weakened:Bool = false //flag to be stolen //MARK: - Init - convenience override init(){ var bulletEffects: [BulletEffectProtocol] = [TextureBulletEffect(textureName: "lineBullet"), FireDelayBulletEffect(delay: 3.5), SpeedBulletEffect(speed: 8), LinePathBulletEffect(direction: Directions.Down), StandardSpawnBulletEffect()] self.init(textureName: "enemy", bulletEffects: bulletEffects, numBullets: 1, bulletCount: 20, speed: 5, name: "enemy") } //Init using set properties init(textureName: String, bulletEffects: [BulletEffectProtocol], numBullets:UInt, bulletCount: UInt, speed:CGFloat, name:String) { var texture = SKTexture(imageNamed: textureName) super.init(texture: texture, color: UIColor.clearColor(), size: texture.size()) self.gun = Gun(initialEffects: bulletEffects, numberOfBulletsToFire: numBullets, bulletCount: bulletCount, owner: self) self.gun.setPhysicsBody(CollisionCategories.EnemyBullet, contactBit: CollisionCategories.Player, collisionBit: CollisionCategories.None) self.speed = speed self.name = name self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame) self.physicsBody?.dynamic = true self.physicsBody?.categoryBitMask = CollisionCategories.Enemy self.physicsBody?.contactTestBitMask = CollisionCategories.PlayerBullet self.physicsBody?.collisionBitMask = CollisionCategories.None self.physicsBody?.usesPreciseCollisionDetection = false } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) fatalError("init(coder:) has not been implemented") } //MARK: - Methods - //Add path for movement func addPath(path:UIBezierPath) { self.movementPath = path } //MARK: - Update - func update(deltaTime: CFTimeInterval){ gun.update(deltaTime) //Shoot whenever you can if gun.canShoot && !weakened { gun.shoot() } } //Function to perform when player steals this character's ability func steal(player:Player){ } //Function called when about to die func willDie(){ self.removeAllActions() self.removeFromParent() bulletManager.returnBullets(gun.bulletPool) } //separate add function to add all components before being put onto screen func addToScene(scene:SKScene){ var moveAction = SKAction.followPath(movementPath!.CGPath, asOffset: true, orientToPath: true, speed: self.speed) var removeAction = SKAction.removeFromParent() var onScreenActionGrp = SKAction.sequence([moveAction, removeAction]) scene.addChild(self) self.runAction(onScreenActionGrp) } }
mit
04a9f10df5756ae4132ca2826c3666d9
35.843373
243
0.682368
4.50885
false
false
false
false
ColinEberhardt/ReactiveTwitterSearch
ReactiveTwitterSearch/Util/TableViewBindingHelper.swift
1
2740
// // TableViewBindingHelper.swift // ReactiveSwiftFlickrSearch // // Created by Colin Eberhardt on 15/07/2014. // Copyright (c) 2014 Colin Eberhardt. All rights reserved. // import UIKit import ReactiveCocoa import Result @objc protocol ReactiveView { func bindViewModel(viewModel: AnyObject) } // a helper that makes it easier to bind to UITableView instances // see: http://www.scottlogic.com/blog/2014/05/11/reactivecocoa-tableview-binding.html class TableViewBindingHelper<T: AnyObject> : NSObject { //MARK: Properties var delegate: UITableViewDelegate? private let tableView: UITableView private let templateCell: UITableViewCell private let selectionCommand: RACCommand? private let dataSource: DataSource //MARK: Public API init(tableView: UITableView, sourceSignal: SignalProducer<[T], NoError>, nibName: String, selectionCommand: RACCommand? = nil) { self.tableView = tableView self.selectionCommand = selectionCommand let nib = UINib(nibName: nibName, bundle: nil) // create an instance of the template cell and register with the table view templateCell = nib.instantiateWithOwner(nil, options: nil)[0] as! UITableViewCell tableView.registerNib(nib, forCellReuseIdentifier: templateCell.reuseIdentifier!) dataSource = DataSource(data: nil, templateCell: templateCell) super.init() sourceSignal.startWithNext { [weak self] data in self?.dataSource.data = data.map({ $0 as AnyObject }) self?.tableView.reloadData() } self.tableView.dataSource = dataSource self.tableView.delegate = dataSource self.tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 100.0 } } class DataSource: NSObject, UITableViewDataSource, UITableViewDelegate { private let templateCell: UITableViewCell var data: [AnyObject]? init(data: [AnyObject]?, templateCell: UITableViewCell) { self.data = data self.templateCell = templateCell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data?.count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCellWithIdentifier(templateCell.reuseIdentifier!), item = data?.safeIndex(indexPath.row), reactiveView = cell as? ReactiveView else { return UITableViewCell() } reactiveView.bindViewModel(item) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { /* if selectionCommand != nil { selectionCommand?.execute(data[indexPath.row]) }*/ } }
mit
4975ab87b42b018f49fdd1680c56ebc7
30.136364
130
0.727372
5.009141
false
false
false
false
coolryze/YZPlayer
YZPlayerDemo/YZPlayerDemo/Tools/UIBarButtonItem+Extension.swift
1
1367
// // UIBarButtonItem+Extension.swift // MU // // Created by heyuze on 16/7/11. // Copyright © 2016年 HYZ. All rights reserved. // import UIKit extension UIBarButtonItem { // 分类里 使用遍历构造器 convenience init(imageName: String? = nil, title: String? = nil, target: AnyObject?, action: Selector) { self.init() //遍历构造器必须调用自己的init let button = UIButton() if imageName != nil { button.setImage(UIImage(named: imageName!), for: .normal) // button.setImage(UIImage(named: "\(imageName!)_highlighted"), forState: UIControlState.Highlighted) button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 0) } if title != nil { button.setTitle(title!, for: .normal) // 设置字体的大小颜色 button.titleLabel?.font = UIFont.systemFont(ofSize: 13) button.setTitleColor(BLACK, for: .normal) button.setTitleColor(BLUE, for: .highlighted) button.setTitleColor(RGB(r: 0x66, g: 0x66, b: 0x66, alpha: 0.3), for: .disabled) } button.addTarget(target, action: action, for: UIControlEvents.touchUpInside) button.sizeToFit() customView = button } }
mit
fe0a32a4c40ef725f5d98e4fa01a19d6
29.27907
112
0.578341
4.120253
false
false
false
false
SoneeJohn/WWDC
WWDC/MultipleChoiceFilter.swift
1
4066
// // MultipleChoiceFilter.swift // WWDC // // Created by Guilherme Rambo on 27/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Foundation struct FilterOption: Equatable { let title: String let value: String let isNegative: Bool init(title: String, value: String, isNegative: Bool = false) { self.title = title self.value = value self.isNegative = isNegative } func negated(with newTitle: String) -> FilterOption { return FilterOption(title: newTitle, value: value, isNegative: true) } static func ==(lhs: FilterOption, rhs: FilterOption) -> Bool { return lhs.value == rhs.value && lhs.isNegative == rhs.isNegative && lhs.title == rhs.title } func dictionaryRepresentation() -> [String : String] { var dictionary = [String : String]() dictionary["value"] = value dictionary["title"] = title return dictionary } } extension Array where Element == FilterOption { init?(_ fromArray: Array<Any>?) { guard let fromArray = fromArray as? Array<Dictionary<String, String>> else { return nil } self = Array<FilterOption>() for i in fromArray { if let title = i["title"], let value = i["value"] { append(FilterOption(title: title, value: value)) } } } func dictionaryRepresentation() -> Array<Dictionary<String, String>> { var array = Array<Dictionary<String, String>>() for option in self { array.append(option.dictionaryRepresentation()) } return array } } struct MultipleChoiceFilter: FilterType { var identifier: String var isSubquery: Bool var collectionKey: String var modelKey: String var options: [FilterOption] private var _selectedOptions: [FilterOption] = [FilterOption]() var selectedOptions: [FilterOption] { get { return _selectedOptions } set { // For state preservation we ensure that selected options are actually part of the options that are available on this filter _selectedOptions = newValue.filter { options.contains($0) } } } var emptyTitle: String var isEmpty: Bool { return selectedOptions.isEmpty } var title: String { if isEmpty || selectedOptions.count == options.count { return emptyTitle } else { let t = selectedOptions.reduce("", { $0 + ", " + $1.title }) guard !t.isEmpty else { return t } return String(t[t.index(t.startIndex, offsetBy: 2)...]) } } var predicate: NSPredicate? { guard !isEmpty else { return nil } let subpredicates = selectedOptions.map { option -> NSPredicate in let format: String let op = option.isNegative ? "!=" : "==" if isSubquery { format = "SUBQUERY(\(collectionKey), $\(collectionKey), $\(collectionKey).\(modelKey) \(op) %@).@count > 0" } else { format = "\(modelKey) \(op) %@" } return NSPredicate(format: format, option.value) } return NSCompoundPredicate(orPredicateWithSubpredicates: subpredicates) } init(identifier: String, isSubquery: Bool, collectionKey: String, modelKey: String, options: [FilterOption], selectedOptions: [FilterOption], emptyTitle: String) { self.identifier = identifier self.isSubquery = isSubquery self.collectionKey = collectionKey self.modelKey = modelKey self.options = options self.emptyTitle = emptyTitle // Computed property self.selectedOptions = selectedOptions } func dictionaryRepresentation() -> WWDCFilterTypeDictionary { var dictionary: WWDCFilterTypeDictionary = WWDCFilterTypeDictionary() dictionary["selectedOptions"] = selectedOptions.dictionaryRepresentation() return dictionary } }
bsd-2-clause
07981d8a469575baa1bfe53065d4b67f
27.034483
167
0.608856
4.726744
false
false
false
false
twg/TWGExtensions
Example/Tests/NSString+TWGEmailValidatorTests.swift
1
1184
import Foundation import XCTest import TWGExtensions class NSString_TWGEmailValidatorTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testEmailValidation() { let invalidEmail1 = "[email protected] m" let invalidEmail2 = "thisisan [email protected]" let invalidEmail3 = "thisisaninvalidemail@dsd s.com" let invalidEmail4 = "thisisaninvalidemail@dsds." let invalidEmail5 = "thisisaninvalidemail@dsds" let invalidEmail6 = "thisisaninvalidemail@" let invalidEmail7 = "thisisaninvalidemail" let validEmail = "[email protected]" XCTAssertFalse(invalidEmail1.isValidEmail()) XCTAssertFalse(invalidEmail2.isValidEmail()) XCTAssertFalse(invalidEmail3.isValidEmail()) XCTAssertFalse(invalidEmail4.isValidEmail()) XCTAssertFalse(invalidEmail5.isValidEmail()) XCTAssertFalse(invalidEmail6.isValidEmail()) XCTAssertFalse(invalidEmail7.isValidEmail()) XCTAssertTrue(validEmail.isValidEmail()) } }
mit
c2fd2aa852d1b268de09ac8e4eb47d23
31
60
0.679054
4.519084
false
true
false
false
ixx1232/SwiftBlank
SwiftBlank/SwiftBlank/TableVC6.swift
1
3266
// // TableVC6.swift // SwiftBlank // // Created by apple on 16/1/20. // Copyright © 2016年 www.ixx.com. All rights reserved. // import UIKit class TableVC6: UIViewController { /// 表格视图 - 属性, 变量 /// lazy 关键字, 允许变量在第一次使用的时候在被实例化 /// 使用了 lazy 之后, 需要有配对的 设置数值的方法 lazy var tableView: UITableView? = { print("懒加载了.....") // tableView 的初始化代码 // 实例化表格视图, 添加到 self.view // 注意: 内部不能直接使用自己 let view = UITableView(frame: self.view.bounds, style: UITableViewStyle.Plain) // 指定表格的数据源方法, 此时必须要遵守协议 view.dataSource = self return view }() lazy var persons: [Person]? = { // 实例化数组 let array = [Person(name: "张三", age: 18), Person(name: "张三 - 123", age: 18), Person(name: "张三 - 456", age: 18), Person(name: "张三 - 789", age: 18)] return array }() override func viewDidLoad() { super.viewDidLoad() print("开始添加表格视图.......") // 之所以要使用 ! 是因为定义时, 对象可以为空 // 而 addSubView 函数不能接nil, 必须要有值 self.view.addSubview(tableView!) } } // MARK: - 表格数据源扩展 // 利用 extension 可以将某一类相关代码写在一起 - 优雅 extension TableVC6: UITableViewDataSource { // 注意: 在扩展中, 不能包含存储的属性 // var str = "zhangsan" // MARK: - 数据源方法 func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return persons!.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as? MyCCell // 如果 cell 不存在, 创建一个 cell if cell == nil { // 实例化一个 cell cell = MyCCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell") } // 设置内容 // cell!.textLabel?.text = "我是老五 \(indexPath.row)" cell!.person = persons![indexPath.row] return cell! } } /// 自定义 Cell - 私有类 作用域就在当前文件中!文件外部的类都无法访问 /** MVVM -> 设计模式的目的就是减少控制器的压力! * 模型可能会被很多类调用,不能私有 * 自定义 Cell 通常就是自己在用,完全可以私有! */ private class MyCCell: UITableViewCell { // 定义模型 var person: Person? { // didSet 可以做到给属性设置数值之后,去做一些事情 didSet { // 结果会是完整的字符串 self.textLabel!.text = "\(person!.name!) --- \(person!.age!)" } } }
apache-2.0
15b9da0014063cb4a4b25f579b0df1dc
22.035398
109
0.543604
3.867756
false
false
false
false
nifty-swift/Nifty
Tests/NiftyTests/cross_test.swift
2
1524
/*************************************************************************************************** * cross_test.swift * * This file tests the cross function. * * Author: Philip Erickson * Creation Date: 22 Jan 2017 * * 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. * * Copyright 2017 Philip Erickson **************************************************************************************************/ import XCTest @testable import Nifty class cross_test: XCTestCase { #if os(Linux) static var allTests: [XCTestCaseEntry] { let tests = [ testCase([("testBasic", cross_test.testBasic)]), ] return tests } #endif func testBasic() { let v1 = Vector([1.0, 345.35, 2342564.453]) let v2 = Vector([5.6, 4.5, 4254.3]) let x = cross(v1, v2) print(x) XCTAssert(x.data == [-0.90723175335E7, 1.31141066368E7, -0.000192946E7]) // FIXME: use compare with precision } }
apache-2.0
e61f473786046f69099f0b7f76d68349
30.102041
117
0.553806
4.256983
false
true
false
false
RMizin/PigeonMessenger-project
FalconMessenger/ChatsControllers/ViewBlockerContainer.swift
1
4269
// // ViewBlockerContainer.swift // FalconMessenger // // Created by Roman Mizin on 9/18/18. // Copyright © 2018 Roman Mizin. All rights reserved. // import UIKit class ViewBlockerContainer: UIView { let label: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.numberOfLines = 0 label.textAlignment = .center label.sizeToFit() label.textColor = ThemeManager.currentTheme().supplementaryViewTextColor label.backgroundColor = .clear label.font = UIFont.boldSystemFont(ofSize: 16) label.text = "This user is not in your Falcon Contacts" return label }() let show: UIButton = { let show = UIButton() show.translatesAutoresizingMaskIntoConstraints = false show.setTitle("Show", for: .normal) show.contentHorizontalAlignment = .center show.contentVerticalAlignment = .center show.titleLabel?.sizeToFit() show.backgroundColor = ThemeManager.currentTheme().controlButtonColor show.layer.cornerRadius = 25 show.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) show.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18) show.addTarget(self, action: #selector(ChatLogViewController.removeBlockerView), for: .touchUpInside) return show }() let blockAndDelete: UIButton = { let blockAndDelete = UIButton() blockAndDelete.translatesAutoresizingMaskIntoConstraints = false blockAndDelete.setTitle("Block And Delete", for: .normal) blockAndDelete.setTitleColor(FalconPalette.dismissRed, for: .normal) blockAndDelete.contentHorizontalAlignment = .center blockAndDelete.contentVerticalAlignment = .center blockAndDelete.titleLabel?.sizeToFit() blockAndDelete.backgroundColor = ThemeManager.currentTheme().controlButtonColor blockAndDelete.layer.cornerRadius = 25 blockAndDelete.titleEdgeInsets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10) blockAndDelete.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18) blockAndDelete.addTarget(self, action: #selector(ChatLogViewController.blockAndDelete), for: .touchUpInside) return blockAndDelete }() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = ThemeManager.currentTheme().generalBackgroundColor show.setTitleColor(ThemeManager.currentTheme().tintColor, for: .normal) addSubview(label) label.topAnchor.constraint(equalTo: topAnchor, constant: 40).isActive = true if #available(iOS 11.0, *) { label.leftAnchor.constraint(equalTo: safeAreaLayoutGuide.leftAnchor, constant: 10).isActive = true label.rightAnchor.constraint(equalTo: safeAreaLayoutGuide.rightAnchor, constant: -10).isActive = true } else { label.leftAnchor.constraint(equalTo: leftAnchor, constant: 10).isActive = true label.rightAnchor.constraint(equalTo: rightAnchor, constant: -10).isActive = true } addSubview(show) addSubview(blockAndDelete) show.topAnchor.constraint(equalTo: label.bottomAnchor, constant: 40).isActive = true show.rightAnchor.constraint(equalTo: label.rightAnchor).isActive = true show.leftAnchor.constraint(equalTo: label.leftAnchor).isActive = true show.heightAnchor.constraint(equalToConstant: 55).isActive = true blockAndDelete.topAnchor.constraint(equalTo: show.bottomAnchor, constant: 20).isActive = true blockAndDelete.rightAnchor.constraint(equalTo: label.rightAnchor).isActive = true blockAndDelete.leftAnchor.constraint(equalTo: label.leftAnchor).isActive = true blockAndDelete.heightAnchor.constraint(equalToConstant: 55).isActive = true NotificationCenter.default.addObserver(self, selector: #selector(changeTheme), name: .themeUpdated, object: nil) } deinit { NotificationCenter.default.removeObserver(self) } @objc func changeTheme() { backgroundColor = ThemeManager.currentTheme().generalBackgroundColor } func remove(from view: UIView) { for subview in view.subviews where subview is ViewBlockerContainer { DispatchQueue.main.async { subview.removeFromSuperview() } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-3.0
a9a0f942ba15140f690dfbb3ace66b27
37.45045
116
0.740159
4.779395
false
false
false
false
nickfalk/BSImagePicker
Pod/Classes/Controller/ZoomAnimator.swift
1
4725
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // 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 UIImageViewModeScaleAspect final class ZoomAnimator : NSObject, UIViewControllerAnimatedTransitioning { var sourceImageView: UIImageView? var destinationImageView: UIImageView? func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { // Get to and from view controller if let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to), let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from), let sourceImageView = sourceImageView, let destinationImageView = destinationImageView{ let containerView = transitionContext.containerView // Disable selection so we don't select anything while the push animation is running fromViewController.view?.isUserInteractionEnabled = false // Setup views sourceImageView.isHidden = true destinationImageView.isHidden = true toViewController.view.alpha = 0.0 fromViewController.view.alpha = 1.0 containerView.backgroundColor = toViewController.view.backgroundColor // Setup scaling image let scalingFrame = containerView.convert(sourceImageView.frame, from: sourceImageView.superview) let scalingImage = UIImageViewModeScaleAspect(frame: scalingFrame) scalingImage.contentMode = sourceImageView.contentMode scalingImage.image = sourceImageView.image // Setup image aspect let contentModeIsFit = destinationImageView.contentMode == .scaleAspectFit let scaleAspect: UIImageViewModeScaleAspect.ScaleAspect = contentModeIsFit ? .fit : .fill //Init image scale let destinationFrame = toViewController.view.convert(destinationImageView.bounds, from: destinationImageView.superview) scalingImage.initialeState(scaleAspect, newFrame: destinationFrame) // Add views to container view containerView.addSubview(toViewController.view) containerView.addSubview(scalingImage) // Animate UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, options: UIViewAnimationOptions(), animations: { () -> Void in // Fade in fromViewController.view.alpha = 0.0 toViewController.view.alpha = 1.0 scalingImage.transitionState(scaleAspect) }, completion: { (finished) -> Void in // Finish image scaling and remove image view scalingImage.endState(scaleAspect) scalingImage.removeFromSuperview() // Unhide destinationImageView.isHidden = false sourceImageView.isHidden = false fromViewController.view.alpha = 1.0 // Finish transition transitionContext.completeTransition(!transitionContext.transitionWasCancelled) // Enable selection again fromViewController.view?.isUserInteractionEnabled = true }) } } }
mit
bdf2a15532ef0bff09045850769598a9
49.255319
314
0.667231
6.159061
false
false
false
false
bingoogolapple/SwiftNote-PartOne
模态窗口-Storyboard/模态窗口-Storyboard/ViewController.swift
1
2005
// // ViewController.swift // 模态窗口-Storyboard // // Created by bingoogol on 14/10/3. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit /** segue直接从Controller连接到Controller */ class ViewController: UIViewController,LoginViewControllerDelegate,UIActionSheetDelegate { @IBOutlet weak var loginBtn: UIBarButtonItem! @IBOutlet weak var messageLabel: UILabel! var isLogon:Bool = false override func viewDidLoad() { super.viewDidLoad() } @IBAction func login(sender: UIBarButtonItem) { if self.isLogon { var sheet = UIActionSheet(title: "是否注销", delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: "注销") sheet.showInView(self.view) } else { // 因为在Storyboard中已经定义了login视图控制器,因此在此不能实例化新的LoginViewController // var controller = LoginViewController() // self.presentViewController(controller, animated: true, completion: nil) // segue直接从Controller连接到Controller self.performSegueWithIdentifier("LoginSegue", sender: nil) } } func loginViewLogonSuccessedWithUsername(username: NSString) { messageLabel.text = username loginBtn.title = "注销" isLogon = true } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if ("LoginSegue" as NSString).isEqualToString(segue.identifier!) { var controller = segue.destinationViewController as LoginViewController controller.delegate = self } } func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int) { println("\(buttonIndex)") if buttonIndex == 0 { messageLabel.text = "用户未登陆" loginBtn.title = "登陆" isLogon = false } } }
apache-2.0
37db306317914cab6d7380b66b4b2d3d
29.918033
123
0.640849
4.921671
false
false
false
false
louisdh/lioness
Sources/Lioness/AST/Nodes/BooleanNode.swift
1
1085
// // BooleanNode.swift // Lioness // // Created by Louis D'hauwe on 15/10/2016. // Copyright © 2016 - 2017 Silver Fox. All rights reserved. // import Foundation public struct BooleanNode: ASTNode { /// Either 0 (false) or 1 (true) public let value: UInt8 public var boolValue: Bool { return value == 1 } public init?(value: UInt8) { if value != 0 && value != 1 { return nil } self.value = value } public init(bool: Bool) { if bool == true { self.value = 1 } else { self.value = 0 } } public func compile(with ctx: BytecodeCompiler, in parent: ASTNode?) throws -> BytecodeBody { let label = ctx.nextIndexLabel() return [BytecodeInstruction(label: label, type: .pushConst, arguments: [.value(.bool(boolValue))])] } public var childNodes: [ASTNode] { return [] } public var description: String { return "BooleanNode(\(value))" } public var nodeDescription: String? { if boolValue == true { return "true" } else { return "false" } } public var descriptionChildNodes: [ASTChildNode] { return [] } }
mit
9b34813f20dd722d8bb8da138f083242
14.485714
101
0.640221
3.123919
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/External/RCEmojiKit/Emojione+Transform.swift
1
2415
// // Emojione+Transform.swift // Rocket.Chat // // Created by Matheus Cardoso on 2/26/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import Foundation extension Emojione { static func transform(string: String) -> String { var validString = string as NSString var notMatched = [NSRange]() var ranges = getMatches(from: validString) (validString, notMatched) = insertEmojis(into: validString, in: (validString as String).filterOutRangesInsideCode(ranges: ranges)) ranges = getMatches(from: validString, excludingRanges: notMatched) (validString, _) = insertEmojis(into: validString, in: (validString as String).filterOutRangesInsideCode(ranges: ranges)) return validString as String } static func getMatches(from string: NSString, excludingRanges: [NSRange] = []) -> [NSRange] { var ranges = [NSRange]() var lastMatchIndex = 0 for range in excludingRanges { ranges.append(NSRange(location: lastMatchIndex, length: range.location - lastMatchIndex + 1)) lastMatchIndex = range.location + range.length - 1 } ranges.append(NSRange(location: lastMatchIndex, length: string.length - lastMatchIndex)) let regex = try? NSRegularExpression(pattern: ":(\\w|-|\\+)+:", options: []) let matchRanges = ranges.map { range in regex?.matches(in: string as String, options: [], range: range).map { $0.range(at: 0) } ?? [] } return matchRanges.reduce(into: [NSRange]()) { $0.append(contentsOf: $1) } } static func insertEmojis(into string: NSString, in ranges: [NSRange]) -> (string: NSString, notMatched: [NSRange]) { var offset = 0 var string = string var notMatched = [NSRange]() for range in ranges { let transformedRange = NSRange(location: range.location - offset, length: range.length) let replacementString = string.substring(with: transformedRange) as NSString if let emoji = values[replacementString.replacingOccurrences(of: ":", with: "")] { string = string.replacingCharacters(in: transformedRange, with: emoji) as NSString offset += replacementString.length - (emoji as NSString).length } else { notMatched.append(transformedRange) } } return (string, notMatched) } }
mit
0399ebf5f5d6b08c87a9ee0a8e06ebc6
41.350877
143
0.643331
4.478664
false
false
false
false
luispadron/GradePoint
GradePoint/Controllers/Settings/GradeBird/GameViewController.swift
1
1517
// // GameViewController.swift // GradePoint // // Created by Luis Padron on 1/30/18. // Copyright © 2018 Luis Padron. All rights reserved. // import SpriteKit import UIKit class GameViewController: UIViewController { // MARK: View life cycle private lazy var skView: SKView = { let view = SKView() view.autoresizingMask = [.flexibleWidth, .flexibleHeight] return view }() override func viewDidLoad() { super.viewDidLoad() // Set up sprite kit view if !self.view.subviews.contains(skView) { self.view.addSubview(skView) self.skView.frame = self.view.frame } self.skView.showsFPS = true self.skView.showsNodeCount = false self.skView.ignoresSiblingOrder = false // Setup scene let scene = GameScence(size: self.view.bounds.size) scene.scaleMode = .resizeFill scene.gameController = self self.skView.presentScene(scene) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.setNeedsStatusBarAppearanceUpdate() } override var shouldAutorotate: Bool { return false } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if UIDevice.current.userInterfaceIdiom == .phone { return .portrait } else { return .all } } override var prefersStatusBarHidden: Bool { return true } }
apache-2.0
6db74f74f08700d26afcc87a82855178
23.852459
77
0.626649
4.938111
false
false
false
false
mrdepth/Neocom
Neocom/Neocom/Utility/StoreKit+Extensions.swift
2
6426
// // StoreKit+Extensions.swift // Neocom // // Created by Artem Shimanski on 5/24/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // #if !targetEnvironment(macCatalyst) import Foundation import StoreKit import Combine import ASReceipt extension SKProductsRequest { static func productsPublisher(productIdentifiers: Set<String>) -> ProductsRequestPublisher { ProductsRequestPublisher(productIdentifiers: productIdentifiers) } } extension SKProduct { var priceFormatter: NumberFormatter { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = priceLocale return formatter } } struct ProductsRequestPublisher: Publisher { typealias Output = [SKProduct] typealias Failure = SKError var productIdentifiers: Set<String> private class ProductsRequestSubscription<S: Subscriber>: NSObject, SKProductsRequestDelegate, Subscription where S.Failure == Failure, S.Input == Output { var productIdentifiers: Set<String> var request: SKProductsRequest? var subscriber: S init(subscriber: S, productIdentifiers: Set<String>) { self.subscriber = subscriber self.productIdentifiers = productIdentifiers super.init() } func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { _ = subscriber.receive(response.products) } func request(_ request: SKRequest, didFailWithError error: Error) { subscriber.receive(completion: .failure(error as? SKError ?? SKError(SKError.unknown))) } func requestDidFinish(_ request: SKRequest) { subscriber.receive(completion: .finished) } func request(_ demand: Subscribers.Demand) { if request == nil { let request = SKProductsRequest(productIdentifiers: productIdentifiers) request.delegate = self request.start() } } func cancel() { request?.cancel() } } func receive<S>(subscriber: S) where S : Subscriber, Failure == S.Failure, Output == S.Input { subscriber.receive(subscription: ProductsRequestSubscription(subscriber: subscriber, productIdentifiers: productIdentifiers)) } } extension SKProductSubscriptionPeriod { var localizedDescription: String { switch unit { case .day: return String.localizedStringWithFormat(NSLocalizedString("%d days", comment: ""), numberOfUnits) case .month: return String.localizedStringWithFormat(NSLocalizedString("%d months", comment: ""), numberOfUnits) case .week: return String.localizedStringWithFormat(NSLocalizedString("%d weeks", comment: ""), numberOfUnits) case .year: return String.localizedStringWithFormat(NSLocalizedString("%d years", comment: ""), numberOfUnits) @unknown default: return "unknown" } } } struct RestoreCompletedTransactionsPublisher: Publisher { typealias Output = [SKPaymentTransaction] typealias Failure = Error func receive<S>(subscriber: S) where S : Subscriber, Self.Failure == S.Failure, Self.Output == S.Input { subscriber.receive(subscription: RestoreCompletedTransactionsSubscription(subscriber: subscriber)) } private class RestoreCompletedTransactionsSubscription<S: Subscriber>: NSObject, SKPaymentTransactionObserver, Subscription where S.Failure == Failure, S.Input == Output { private var restored: [SKPaymentTransaction]? func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { restored?.append(contentsOf: transactions.filter{$0.transactionState == .restored}) } func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) { _ = subscriber.receive(restored ?? []) subscriber.receive(completion: .finished) } func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) { subscriber.receive(completion: .failure(error)) } func request(_ demand: Subscribers.Demand) { if restored == nil { restored = [] let queue = SKPaymentQueue.default() queue.add(self) queue.restoreCompletedTransactions() } } func cancel() { guard restored != nil else {return} restored = nil SKPaymentQueue.default().remove(self) } deinit { cancel() } var subscriber: S init(subscriber: S) { self.subscriber = subscriber super.init() } } } extension Receipt { static func receiptPublisher(refreshIfNeeded: Bool = false) -> AnyPublisher<Receipt, Error> { Deferred { Future { promise in // DispatchQueue.global().async { do { guard let url = Bundle.main.appStoreReceiptURL else {throw RuntimeError.unknown} let receipt = try Receipt(data: Data(contentsOf: url)) promise(.success(receipt)) } catch { promise(.failure(error)) } // } } }.eraseToAnyPublisher() /*// Deferred { () -> AnyPublisher<Receipt, Error> in guard let url = Bundle.main.appStoreReceiptURL else {return Fail(error: RuntimeError.unknown).eraseToAnyPublisher()} let publisher = FileChangesPublisher(path: url.path) .mapError{$0 as Error} if FileManager.default.fileExists(atPath: url.path) { return publisher.merge(with: Just(()).setFailureType(to: Error.self)) .tryMap {try Receipt(data: Data(contentsOf: url))}.eraseToAnyPublisher() } else { return publisher.tryMap {try Receipt(data: Data(contentsOf: url))}.eraseToAnyPublisher() } // }.eraseToAnyPublisher()*/ } } #endif
lgpl-2.1
8cd94d259d01f2a27177dd9320079592
34.893855
175
0.610895
5.640913
false
false
false
false
artsy/eigen
ios/Artsy/View_Controllers/Live_Auctions/LiveAuctionBidViewModel.swift
1
6229
import Foundation import Interstellar // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. 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 } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } enum LiveAuctionBiddingProgressState { case userRegistrationRequired case userRegistrationPending case userRegistrationClosed case biddable(askingPrice: UInt64, currencySymbol: String) case biddingInProgress case bidNotYetAccepted(askingPrice: UInt64, currencySymbol: String) case bidAcknowledged case bidBecameMaxBidder case bidOutbid case bidNetworkFail case bidFailed(reason: String) case lotWaitingToOpen case lotSold } func == (lhs: LiveAuctionBiddingProgressState, rhs: LiveAuctionBiddingProgressState) -> Bool { switch (lhs, rhs) { case (.userRegistrationRequired, .userRegistrationRequired): return true case (.userRegistrationPending, .userRegistrationPending): return true case (.userRegistrationClosed, .userRegistrationClosed): return true case (.biddable(let lhsState), .biddable(let rhsState)) where lhsState.askingPrice == rhsState.askingPrice && lhsState.currencySymbol == rhsState.currencySymbol: return true case (.biddingInProgress, .biddingInProgress): return true case (.bidBecameMaxBidder, .bidBecameMaxBidder): return true case (.bidNotYetAccepted(let lhsState), .bidNotYetAccepted(let rhsState)) where lhsState.askingPrice == rhsState.askingPrice && lhsState.currencySymbol == rhsState.currencySymbol: return true case (.bidAcknowledged, .bidAcknowledged): return true case (.bidNetworkFail, .bidNetworkFail): return true case (.lotWaitingToOpen, .lotWaitingToOpen): return true case (.lotSold, .lotSold): return true case (.bidOutbid, .bidOutbid): return true default: return false } } class LiveAuctionBidViewModel: NSObject { let lotViewModel: LiveAuctionLotViewModelType let salesPerson: LiveAuctionsSalesPersonType // This mutates as someone increments/decrements, first set in the initializer. var currentBid: UInt64 = 0 // For a stepper UI, a better data structure would be a doubly-linked list. // But we're switching to a UI that will be best with an array: https://github.com/artsy/eigen/issues/1579 fileprivate var bidIncrements: [UInt64] = [] init(lotVM: LiveAuctionLotViewModelType, salesPerson: LiveAuctionsSalesPersonType) { self.lotViewModel = lotVM self.salesPerson = salesPerson super.init() currentBid = self.currentAskingPrice bidIncrements = [currentBid] let threshold = 5 * max(lotVM.askingPrice, (lotVM.highEstimateOrEstimateCents ?? 0)) var i = 0 repeat { let nextBid = salesPerson.bidIncrements.minimumNextBidCentsIncrement(bidIncrements[i]) bidIncrements.append(nextBid) i += 1 } while bidIncrements[i] < threshold } var availableIncrements: Int { return bidIncrements.count } func bidIncrementValueAtIndex(_ index: Int) -> UInt64 { return bidIncrements[index] } func bidIncrementStringAtIndex(_ index: Int) -> String { let value = bidIncrements[index] return value.convertToDollarString(lotViewModel.currencySymbol) } var currentAskingPrice: UInt64 { // Should not return 0, this is just to satisfy the compiler. return lotViewModel.askingPriceSignal.peek() ?? 0 } var currentLotAskingPriceString: String { return salesPerson.askingPriceString(lotViewModel) } var currentBidDollars: String { return currentBid.convertToDollarString(lotViewModel.currencySymbol) } var nextBidIncrementDollars: String { let bidIncrementCents = nextBidCents(currentBid) - currentBid return bidIncrementCents.convertToDollarString(lotViewModel.currencySymbol) } var currentBidsAndReserve: String { let bids = lotViewModel.numberOfBids let bidString = bids == 1 ? "\(bids) bid" : "\(bids) bids" return "(\(bidString) \(lotViewModel.reserveStatusString))" } var canMakeLowerBids: Bool { return currentBid > bidIncrements.first } func nextBidCents(_ bid: UInt64) -> UInt64 { return bidIncrements.first { $0 > bid } ?? bid } func previousBidCents(_ bid: UInt64) -> UInt64 { return bidIncrements.last { $0 < bid } ?? bid } } // Bridges BiddingIncrementStrategy ObjC class to a protocol. public protocol BidIncrementStrategyType: Comparable { var from: NSNumber! { get } var amount: NSNumber! { get } } extension BidIncrementStrategy: BidIncrementStrategyType { } public func < <T: BidIncrementStrategyType>(lhs: T, rhs: T) -> Bool { return lhs.from.uint64Value < rhs.from.uint64Value } public func ==<T: BidIncrementStrategyType>(lhs: T, rhs: T) -> Bool { return lhs.from.uint64Value == rhs.from.uint64Value } extension Array where Element: BidIncrementStrategyType { func minimumNextBidCentsIncrement(_ bid: UInt64) -> UInt64 { let matchingIncrement = self.reduce(nil, { (memo, e) -> Element? in // We want to find the first increment whose from exceed bid, and return memo (the increment before it). if e.from.uint64Value > bid { return memo } else { // If we haven't surpassed the bid yet, return the next "previous value" return e } }) ?? last // If we exhausted the list, use the last, largest element. return bid + (matchingIncrement?.amount.uint64Value ?? bid) // Default to satisfy compiler, or an empty strategy from the API (unlikely) } }
mit
0b77c7ff4284b132ead76b124a5783eb
35.215116
195
0.695457
4.322693
false
false
false
false
Wakup/Wakup-iOS-SDK
Wakup/SearchViewController.swift
1
16670
// // SearchViewController.swift // Wuakup // // Created by Guillermo Gutiérrez on 11/5/15. // Copyright (c) 2015 Yellow Pineapple. All rights reserved. // import UIKit import AddressBookUI import CoreLocation import Contacts class SearchViewController: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, CLLocationManagerDelegate, UISearchResultsUpdating { enum Section: Int { case userLocation case companies case tags case locations case history } @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var filterButtonsScrollView: UIScrollView! var categoryButtons: [SearchFilterButton]? var categoryButtonNib = UINib(nibName: "SearchFilterButton", bundle: Bundle(for: SearchViewController.self)) let geocoder = CLGeocoder() let locationManager = CLLocationManager() let searchService = SearchService.sharedInstance let searchController = UISearchController(searchResultsController: nil) var searchCountry: String? { return WakupManager.manager.options.searchCountryCode.flatMap { (Locale.current as NSLocale).displayName(forKey: NSLocale.Key.countryCode, value: $0) } } var searchComplement: String? { return searchCountry.map{", " + $0} } var userLocation: CLLocation? { didSet { reloadData([.userLocation]) } } var searchResult: SearchResult? { didSet { reloadData([.userLocation, .companies, .tags]) } } var placemarks: [CLPlacemark]? { didSet { reloadData([.userLocation, .locations]) } } var searchHistory: [SearchHistory]? { didSet { reloadData([.history]); } } let buttonsPadding: CGFloat = 8 let buttonsSeparation: CGFloat = 8 func configureFilterButtons() { categoryButtons = WakupManager.manager.options.searchCategories?.map { category in let button = categoryButtonNib.instantiate(withOwner: self, options: nil)[0] as! SearchFilterButton button.category = category return button } guard let buttons = categoryButtons , !buttons.isEmpty else { tableView.tableHeaderView = nil return } var previousButton: UIButton? = nil for button in buttons { filterButtonsScrollView.addSubview(button) if let previousButton = previousButton { filterButtonsScrollView.addConstraint(NSLayoutConstraint(item: button, attribute: .left, relatedBy: .equal, toItem: previousButton, attribute: .right, multiplier: 1, constant: buttonsSeparation)) } else { filterButtonsScrollView.addConstraint(NSLayoutConstraint(item: button, attribute: .left, relatedBy: .equal, toItem: filterButtonsScrollView, attribute: .left, multiplier: 1, constant: 0)) } filterButtonsScrollView.addConstraint(NSLayoutConstraint(item: button, attribute: .centerY, relatedBy: .equal, toItem: filterButtonsScrollView, attribute: .centerY, multiplier: 1, constant: 0)) previousButton = button } if let lastButton = previousButton { filterButtonsScrollView.addConstraint(NSLayoutConstraint(item: lastButton, attribute: .right, relatedBy: .equal, toItem: filterButtonsScrollView, attribute: .right, multiplier: 1, constant: 0)) } } func reloadData(_ sections: [Section]?) { if let sections = sections , sections.count > 0 { let indexSet = NSMutableIndexSet() for section in sections { indexSet.add(section.rawValue) } self.tableView.reloadSections(indexSet as IndexSet, with: .none) } else { self.tableView.reloadData() } } func getSelectedCategories() -> [OfferCategory]? { let categories = categoryButtons?.filter{$0.isSelected}.compactMap{$0.category} return categories?.isEmpty ?? true ? nil : categories } func configureSearchBar() { if #available(iOS 11.0, *) { // Setup the Search Controller searchController.searchResultsUpdater = self searchController.obscuresBackgroundDuringPresentation = false searchController.searchBar.placeholder = "SearchBarPlaceholder".i18n() navigationItem.titleView = nil navigationItem.searchController = searchController navigationItem.hidesSearchBarWhenScrolling = false definesPresentationContext = true searchBar = searchController.searchBar } else { // Setup the Search Bar let searchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 260, height: 44)) searchBar.placeholder = "SearchBarPlaceholder".i18n() searchBar.barTintColor = UIColor.clear searchBar.backgroundImage = UIImage() searchBar.scopeBarBackgroundImage = UIImage() searchBar.delegate = self navigationItem.titleView = searchBar self.searchBar = searchBar } } // MARK: UISearchResultsUpdating func updateSearchResults(for searchController: UISearchController) { searchBar(searchController.searchBar, textDidChange: searchController.searchBar.text ?? "") } // MARK: UIView Lifecycle override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self configureFilterButtons() configureSearchBar() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) locationManager.startUpdatingLocation() searchHistory = searchService.getSavedHistory() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) locationManager.stopUpdatingLocation() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let offset = (filterButtonsScrollView.frame.width - filterButtonsScrollView.contentSize.width) / 2 filterButtonsScrollView.contentInset = UIEdgeInsets(top: 0, left: max(buttonsPadding, offset), bottom: 0, right: buttonsPadding) } // MARK: UISearchBarDelegate func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText == "" { searchResult = .none placemarks = .none return } delay(0.2) { if (searchBar.text ?? "") != searchText { return } self.searchService.genericSearch(searchText, completion: { (result, error) in if (searchBar.text ?? "") != searchText { return } if let error = error { // TODO: Show error to user NSLog("Received error searching: \(error)") self.searchResult = .none } else if let result = result { NSLog("Received companies \(result.companies.map { $0.name })") self.searchResult = result } }) self.geocoder.geocodeAddressString(searchText + (self.searchComplement ?? ""), completionHandler: { (results, error) in if (searchBar.text ?? "") != searchText { return } if let error = error { // TODO: Show error to user NSLog("Received error searching placemarks: \(error)") self.placemarks = .none } else if let results = results { NSLog("Received placemarks \(results.map { $0.name })") self.placemarks = results } }) } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.endEditing(false) } // MARK: UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return Section.history.rawValue + 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let section = Section(rawValue: section) { switch section { case .companies: return searchResult?.companies.count ?? 0 case .tags: return searchResult?.tags.count ?? 0 case .locations: return placemarks?.count ?? 0 case .userLocation: if userLocation != .none && placemarks?.count ?? 0 == 0 && searchResult?.companies.count ?? 0 == 0 { return 1 } case .history: return searchHistory?.count ?? 0 } } return 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: SearchResultCell! if let section = Section(rawValue: (indexPath as NSIndexPath).section) { switch section { case .companies: cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? SearchResultCell let company = searchResult?.companies[(indexPath as NSIndexPath).row] cell.textLabel?.text = company?.name cell.iconIdentifier = "star" case .tags: cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? SearchResultCell let tag = searchResult?.tags[(indexPath as NSIndexPath).row] cell.textLabel?.text = "#" + tag! cell.iconIdentifier = "tag" case .locations: cell = tableView.dequeueReusableCell(withIdentifier: "SubtitleCell") as? SearchResultCell let placemark = placemarks?[(indexPath as NSIndexPath).row] let name = placemark?.name ?? "" let addressFormatter = CNPostalAddressFormatter() if let address = placemark?.postalAddress { cell.detailTextLabel?.text = addressFormatter.string(from: address) } else { cell.detailTextLabel?.text = "" } cell.textLabel?.text = name cell.iconIdentifier = "location" case .userLocation: cell = tableView.dequeueReusableCell(withIdentifier: "FeaturedCell") as? SearchResultCell cell.textLabel?.text = "SearchCellUserLocation".i18n() cell.iconIdentifier = "location" case .history: if let history = searchHistory?[(indexPath as NSIndexPath).row] { switch history { case .location(let name, let address, _, _): cell = tableView.dequeueReusableCell(withIdentifier: "SubtitleCell") as? SearchResultCell cell.textLabel?.text = name cell.detailTextLabel?.text = address cell.iconIdentifier = "location" case .company(_, let name): cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? SearchResultCell cell.textLabel?.text = name cell.iconIdentifier = "star" case .tag(let tag): cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as? SearchResultCell cell.textLabel?.text = "#" + tag cell.iconIdentifier = "tag" } } } } return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let section = Section(rawValue: section) { switch section { case .companies: if (searchResult?.companies.count ?? 0) > 0 { return "SearchHeaderCompanies".i18n() } case .tags: if (searchResult?.tags.count ?? 0) > 0 { return "SearchHeaderTags".i18n() } case .locations: if (placemarks?.count ?? 0) > 0 { return "SearchHeaderLocations".i18n() } case .userLocation: break case .history: if searchHistory?.count ?? 0 > 0 { return "SearchHeaderHistory".i18n() } break } } return .none } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let searchTerm: String? = nil var companyId: Int? var companyName: String? var location: CLLocation? var locationName: String? var selectedTag: String? var newHistory: SearchHistory? = .none if let section = Section(rawValue: (indexPath as NSIndexPath).section) { switch section { case .companies: if let company = searchResult?.companies[(indexPath as NSIndexPath).row] { companyId = company.id companyName = company.name newHistory = .company(id: company.id, name: company.name) } case .tags: if let tag = searchResult?.tags[(indexPath as NSIndexPath).row] { selectedTag = tag newHistory = .tag(tag: tag) } case .locations: if let placemark = placemarks?[(indexPath as NSIndexPath).row], let coord = placemark.location?.coordinate { location = placemark.location locationName = placemark.name let addressFormatter = CNPostalAddressFormatter() var fullAddress = "" if let address = placemark.postalAddress { fullAddress = addressFormatter.string(from: address) } newHistory = SearchHistory.location(name: placemark.name!, address: fullAddress, latitude: coord.latitude, longitude: coord.longitude) } case .userLocation: break case .history: if let history = searchHistory?[(indexPath as NSIndexPath).row] { newHistory = history switch history { case .location(let name, _, let latitude, let longitude): locationName = name location = CLLocation(latitude: latitude, longitude: longitude) case .company(let id, let name): companyId = id companyName = name case .tag(let tag): selectedTag = tag } } break } } if let newHistory = newHistory { searchService.addToHistory(newHistory) } let categories = getSelectedCategories() var tags = categories?.flatMap { $0.associatedTags } ?? [] if let tag = selectedTag { tags.append(tag) } let filterOptions = FilterOptions(searchTerm: searchTerm, tags: tags, companyId: companyId) if let couponVC = storyboard?.instantiateViewController(withIdentifier: CouponWaterfallViewController.storyboardId) as? CouponWaterfallViewController { couponVC.forcedLocation = location couponVC.filterOptions = filterOptions couponVC.filterTitle = companyName ?? locationName ?? selectedTag.map{"#\($0)"} ?? "SearchResults".i18n() navigationController?.pushViewController(couponVC, animated: true) } Async.main(after: 0.1) { tableView.deselectRow(at: indexPath, animated: false) } } // MARK: CLLocationManagerDelegate func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let newLocation = locations.last else { return } NSLog("Received new location: %@", newLocation) self.userLocation = newLocation manager.stopUpdatingLocation() } }
mit
e3c517b58b2a3fea841f5557c1a78fa0
40.88191
211
0.57352
5.76782
false
false
false
false
athiercelin/Localizations
Localizations/Choose Project/ChooseProjectController+Parser.swift
1
3590
// // ChooseProjectViewController+Parser.swift // Localizations // // Created by Arnaud Thiercelin on 2/14/16. // Copyright © 2016 Arnaud Thiercelin. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial // portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation extension ChooseProjectViewController { func parseTranslations(rawContent: String) -> [Translation] { let lines = rawContent.components(separatedBy: "\n") var translations = [Translation]() var comments = "" for line in lines { if line.characters.count == 0 { continue } if line.characters.first != "\"" { // Comment line or blank lines comments.append(line) comments.append("\n") } else { // line with key let translation = self.splitStringLine(line: line) translation.comments = comments translations.append(translation) comments = "" } } return translations } func splitStringLine(line: String) -> Translation { var foundFirstQuote = false var foundSecondQuote = false var foundThirdQuote = false let foundLastQuote = false var ignoreNextCharacter = false var key = "" var value = "" for index in 0..<line.lengthOfBytes(using: String.Encoding.utf8) { let newIndex = line.index(line.startIndex, offsetBy: index) let character = line[newIndex] if character == "\\" { if !ignoreNextCharacter { ignoreNextCharacter = true continue } } if !foundFirstQuote { if !ignoreNextCharacter { if character == "\"" { foundFirstQuote = true ignoreNextCharacter = false continue } } } else { if !foundSecondQuote { if !ignoreNextCharacter { if character == "\"" { foundSecondQuote = true ignoreNextCharacter = false continue } } else { key += "\\" } key += "\(character)" } else { if !foundThirdQuote { if character == " " || character == "=" { ignoreNextCharacter = false continue } if character == "\"" { foundThirdQuote = true ignoreNextCharacter = false continue } } else { if !foundLastQuote { if !ignoreNextCharacter { if character == "\"" { foundSecondQuote = true ignoreNextCharacter = false break } } else { value += "\\" } value += "\(character)" } else { break } } } } ignoreNextCharacter = false } return Translation(key: key, value: value, comments: "") } }
mit
b0b136ca34cd94f4326a581f6641104b
26.821705
112
0.642797
4.019037
false
false
false
false
BLSSwiftHackaton2015/CrossWatch
CrossWatch/CrossWatch/UserDefaults.swift
1
1501
// // UserDefaults.swift // CrossWatch // // Created by Grzegorz Pawlowicz on 13.06.2015. // Copyright (c) 2015 Grzegorz Pawlowicz. All rights reserved. // import UIKit class UserDefaults: NSObject { static func sendWorkout(workout: Workout){ if var workoutsArray = getWorkouts() { workoutsArray.append(workout) let data = NSKeyedArchiver.archivedDataWithRootObject(workoutsArray) NSUserDefaults.standardUserDefaults().setObject(data, forKey: "WorkoutArray") return } else { var workoutsArray = [workout] let data = NSKeyedArchiver.archivedDataWithRootObject(workoutsArray) NSUserDefaults.standardUserDefaults().setObject(data, forKey: "WorkoutArray") return } } static func sendWorkouts(workoutsArray: Array<Workout>) { for workout in workoutsArray { sendWorkout(workout) } } static func sendNewWorkoutArray(workoutsArray: Array<Workout>) { let data = NSKeyedArchiver.archivedDataWithRootObject(workoutsArray) NSUserDefaults.standardUserDefaults().setObject(data, forKey: "WorkoutArray") } static func getWorkouts() -> Array<Workout>? { let data = NSUserDefaults.standardUserDefaults().valueForKey("WorkoutArray") as! NSData var workoutsArray = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [Workout] return workoutsArray } }
apache-2.0
db9a2b59f099ad73db825c93f0237911
31.630435
95
0.660227
5.193772
false
false
false
false
xwu/swift
test/decl/protocol/req/recursion.swift
1
3048
// RUN: %target-typecheck-verify-swift protocol SomeProtocol { associatedtype T } extension SomeProtocol where T == Optional<T> { } // expected-error{{same-type constraint 'Self.T' == 'Optional<Self.T>' is recursive}} // rdar://problem/19840527 class X<T> where T == X { // expected-error{{same-type constraint 'T' == 'X<T>' is recursive}} // expected-error@-1{{same-type requirement makes generic parameter 'T' non-generic}} var type: T { return Swift.type(of: self) } // expected-error{{cannot convert return expression of type 'X<T>.Type' to return type 'T'}} } // FIXME: The "associated type 'Foo' is not a member type of 'Self'" diagnostic // should also become "associated type 'Foo' references itself" protocol CircularAssocTypeDefault { associatedtype Z = Z // expected-error{{associated type 'Z' references itself}} // expected-note@-1{{type declared here}} // expected-note@-2{{protocol requires nested type 'Z'; do you want to add it?}} associatedtype Z2 = Z3 // expected-note@-1{{protocol requires nested type 'Z2'; do you want to add it?}} associatedtype Z3 = Z2 // expected-note@-1{{protocol requires nested type 'Z3'; do you want to add it?}} associatedtype Z4 = Self.Z4 // expected-error{{associated type 'Z4' references itself}} // expected-note@-1{{type declared here}} // expected-note@-2{{protocol requires nested type 'Z4'; do you want to add it?}} associatedtype Z5 = Self.Z6 // expected-note@-1{{protocol requires nested type 'Z5'; do you want to add it?}} associatedtype Z6 = Self.Z5 // expected-note@-1{{protocol requires nested type 'Z6'; do you want to add it?}} } struct ConformsToCircularAssocTypeDefault : CircularAssocTypeDefault { } // expected-error@-1 {{type 'ConformsToCircularAssocTypeDefault' does not conform to protocol 'CircularAssocTypeDefault'}} // rdar://problem/20000145 public protocol P { associatedtype T } public struct S<A: P> where A.T == S<A> { // expected-error@-1 {{generic struct 'S' has self-referential generic requirements}} // expected-note@-2 {{while resolving type 'S<A>'}} func f(a: A.T) { g(a: id(t: a)) // `a` has error type which is diagnosed as circular reference _ = A.T.self } func g(a: S<A>) { f(a: id(t: a)) _ = S<A>.self } func id<T>(t: T) -> T { return t } } protocol I { init() } protocol PI { associatedtype T : I } struct SI<A: PI> : I where A : I, A.T == SI<A> { // expected-error@-1 {{generic struct 'SI' has self-referential generic requirements}} // expected-note@-2 {{while resolving type 'SI<A>'}} func ggg<T : I>(t: T.Type) -> T { return T() } func foo() { _ = A() _ = A.T() _ = SI<A>() _ = ggg(t: A.self) _ = ggg(t: A.T.self) _ = self.ggg(t: A.self) _ = self.ggg(t: A.T.self) } } // Used to hit infinite recursion struct S4<A: PI> : I where A : I { } struct S5<A: PI> : I where A : I, A.T == S4<A> { } // Used to hit ArchetypeBuilder assertions struct SU<A: P> where A.T == SU { } struct SIU<A: PI> : I where A : I, A.T == SIU { }
apache-2.0
484ce30af9bc38469bb43acd72665d92
28.307692
140
0.648294
3.188285
false
false
false
false
twitterdev/Photobooth
PhotoboothiOS/BoothViewController.swift
1
3651
// // BoothViewController.swift // Photobooth // // Created by Ryan Choi on 4/29/15. // Copyright (c) 2015 Matt Donnelly. All rights reserved. // import Foundation import Foundation import UIKit import MobileCoreServices import TwitterKit class BoothViewController : UIViewController { @IBOutlet weak var navbar: UINavigationItem! // MARK: internal methods func setupNav(_ enableBackButton : Bool, enableSettings : Bool = true, enableLogout : Bool = false){ if let navigationController = self.navigationController { // Get the navigationBar.frame sizes let navHeight = navigationController.navigationBar.frame.height let navWidth = navigationController.navigationBar.frame.width // Create a border let navBorder = UIView(frame: CGRect(x: 0, y: navHeight - 2, width: navWidth, height: 2)) navBorder.tag = 140 // Change the border to blue navBorder.backgroundColor = UIColor(rgba: "#5EA9DD") navigationController.navigationBar.addSubview(navBorder) } if (!enableBackButton){ self.navigationItem.setHidesBackButton(true, animated: true) } if (enableSettings){ // Append image to the navigation bar if let image = UIImage(named: "TwitterLogo") { let logoView = UIImageView(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) logoView.image = image.withRenderingMode(UIImageRenderingMode.alwaysTemplate) logoView.contentMode = UIViewContentMode.scaleAspectFit logoView.frame.origin.x = 10 logoView.frame.origin.y = 8 navbar.titleView = logoView } // Add a tap gesture to the navigation bar image to send the user to settings let recognizer = UITapGestureRecognizer(target: self, action: Selector(("showSettings"))) self.navbar.titleView!.isUserInteractionEnabled = true self.navbar.titleView!.addGestureRecognizer(recognizer) } if enableLogout { // Append image to the navigation bar if let image = UIImage(named: "logout") { let logout: UIButton = UIButton(type: UIButtonType.custom) logout.setBackgroundImage(image, for: UIControlState()) logout.frame = CGRect(x: 0, y: 0, width: 20, height: 20) logout.addTarget(self, action: Selector(("logOut")), for: UIControlEvents.touchUpInside) navbar.rightBarButtonItem = UIBarButtonItem(customView: logout) } } } // MARK: accessors var navigationBarTitle:String { set (newVal) { navbar.title = newVal } get { return navbar.title ?? "" } } // MARK: ovverides override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if let navigationController = self.navigationController, let border = navigationController.navigationBar.viewWithTag(140) { let bounds = navigationController.navigationBar.bounds; border.frame = CGRect(x: 0, y: bounds.height - 2, width: bounds.width, height: 2) } } }
mit
0886afb389134f7e0f9025ef11e972ed
32.190909
104
0.561764
5.634259
false
false
false
false
qualaroo/QualarooSDKiOS
Qualaroo/Survey/SurveyPresenter.swift
1
8083
// // SurveyPresenter.swift // Qualaroo // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation class SurveyPresenter { private weak var surveyViewInterface: SurveyViewInterface? private var interactor: SurveyInteractorProtocol private let theme: Theme private let converter: TextConverter private lazy var factory: QuestionViewFactory = { return QuestionViewFactory(buttonHandler: self, answerHandler: interactor, theme: theme) }() init(theme: Theme, interactor: SurveyInteractorProtocol, converter: TextConverter) { self.theme = theme self.interactor = interactor self.converter = converter configureObservers() } deinit { removeObservers() } // MARK: - Question Logic private func show(_ question: Question) { guard let surveyViewInterface = surveyViewInterface else { interactor.unexpectedErrorOccured("Presenter retained while surveyView is nil.") return } guard let embeddedView = factory.createView(with: question) else { interactor.unexpectedErrorOccured("Couldn't create QuestionView.") return } surveyViewInterface.displayQuestion(viewModel: copyViewModel(with: question), answerView: embeddedView, buttonModel: buttonViewModel(with: question)) } private func show(_ message: Message) { guard let surveyViewInterface = surveyViewInterface else { interactor.unexpectedErrorOccured("Presenter retained while surveyView is nil.") return } surveyViewInterface.displayMessage(withText: converter.convert(message.description), buttonModel: buttonViewModel(with: message), fullscreen: theme.fullscreen) } private func show(_ leadGenForm: LeadGenForm) { guard let surveyViewInterface = surveyViewInterface else { interactor.unexpectedErrorOccured("Presenter retained while surveyView is nil.") return } guard let embeddedView = LeadGenViewBuilder.createView(forLeadGenForm: leadGenForm, buttonHandler: self, answerHandler: interactor, theme: theme) else { interactor.unexpectedErrorOccured("Couldn't create LeadGenView.") return } surveyViewInterface.displayLeadGenForm(with: converter.convert(leadGenForm.description), leadGenView: embeddedView, buttonModel: buttonViewModel(with: leadGenForm)) } } // MARK: - Notifications private extension SurveyPresenter { func configureObservers() { let action = #selector(self.keyboardNotification(notification:)) let notificationName = UIResponder.keyboardWillChangeFrameNotification NotificationCenter.default.addObserver(self, selector: action, name: notificationName, object: nil) } func removeObservers() { NotificationCenter.default.removeObserver(self) } @objc func keyboardNotification(notification: NSNotification) { guard let userInfo = notification.userInfo, let endFrameValue = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue, let animationTime = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval, let surveyViewInterface = surveyViewInterface else { return } let endFrame = endFrameValue.cgRectValue surveyViewInterface.keyboardChangedSize(height: offset(for: endFrame), animationTime: animationTime) } func offset(for keyboardEndFrame: CGRect) -> CGFloat { let isKeyboardHiding = keyboardEndFrame.origin.y >= UIScreen.main.bounds.size.height return isKeyboardHiding ? 0.0 : keyboardEndFrame.size.height } } // MARK: - ViewModels private extension SurveyPresenter { func buttonViewModel(with message: Message) -> SurveyButtonsView.ButtonViewModel { return SurveyButtonsView.ButtonViewModel(text: message.callToAction?.text ?? "", shouldShowButton: message.callToAction != nil) } func buttonViewModel(with question: Question) -> SurveyButtonsView.ButtonViewModel { return SurveyButtonsView.ButtonViewModel(text: question.buttonText, shouldShowButton: question.shouldShowButton) } func buttonViewModel(with leadGen: LeadGenForm) -> SurveyButtonsView.ButtonViewModel { return SurveyButtonsView.ButtonViewModel(text: leadGen.buttonText, shouldShowButton: true) } func copyViewModel(with question: Question) -> SurveyHeaderView.CopyViewModel { return SurveyHeaderView.CopyViewModel(title: converter.convert(question.title), description: converter.convert(question.description), descriptionPlacement: question.descriptionPlacement) } func buttonViewModel(with colors: ColorTheme) -> SurveyButtonsView.ViewModel { return SurveyButtonsView.ViewModel(enabledColor: colors.buttonEnabled, disabledColor: colors.buttonDisabled, textEnabledColor: colors.buttonTextEnabled, textDisabledColor: colors.buttonTextDisabled) } func closeButtonModel(with theme: Theme) -> SurveyHeaderView.CloseButtonViewModel { return SurveyHeaderView.CloseButtonViewModel(color: theme.colors.uiNormal, hidden: !theme.closeButtonVisible) } func surveyBodyViewModel(with theme: Theme) -> SurveyView.BodyViewModel { return SurveyView.BodyViewModel(backgroundColor: theme.colors.background, dimStyle: theme.dimType, dimAlpha: theme.dimAlpha, fullscreen: theme.fullscreen) } } // MARK: - SurveyViewDelegate extension SurveyPresenter: SurveyViewDelegate { func viewLoaded(_ view: SurveyViewInterface) { surveyViewInterface = view let progressViewModel = SurveyView.ProgressViewModel( trackColor: theme.colors.uiNormal, progressColor: theme.colors.uiSelected, location: theme.progressBarLocation ) view.setup(backgroundColor: theme.colors.background, textColor: theme.colors.text, buttonViewModel: buttonViewModel(with: theme.colors), logoUrl: theme.logoUrlString, closeButtonViewModel: closeButtonModel(with: theme), surveyBodyViewModel: surveyBodyViewModel(with: theme), progressViewModel: progressViewModel) interactor.viewLoaded() } func viewDisplayed(_ view: SurveyViewInterface) { if !theme.fullscreen { view.dimBackground() } } func backgroundDimTapped() { interactor.userWantToCloseSurvey() } func nextButtonPressed() { interactor.goToNextNode() } func closeButtonPressed() { interactor.userWantToCloseSurvey() } } // MARK: - SurveyPresenterProtocol extension SurveyPresenter: SurveyPresenterProtocol { func focusOnInput() { surveyViewInterface?.focusOnInput() } func enableButton() { surveyViewInterface?.enableNextButton() } func disableButton() { surveyViewInterface?.disableNextButton() } func present(question: Question) { show(question) } func present(message: Message) { show(message) } func present(leadGenForm: LeadGenForm) { show(leadGenForm) } func closeSurvey() { surveyViewInterface?.closeSurvey(withDim: !theme.fullscreen) } func displayProgress(progress: Float) { surveyViewInterface?.setProgress(progress: progress) } }
mit
66165be145637d3a7eeb17fe1f0cfff9
34.924444
116
0.667079
5.356528
false
false
false
false
Electrode-iOS/ELRouter
ELRouter/Route.swift
2
11049
// // Route.swift // ELRouter // // Created by Brandon Sneed on 10/15/15. // Copyright © 2015 Walmart. All rights reserved. // import Foundation import UIKit import ELFoundation public typealias RouteActionClosure = (_ variable: String?, _ remainingComponents: [String], _ associatedData: inout AssociatedData?) -> Any? @objc public enum RoutingType: UInt { case segue case fixed case push case modal case variable case redirect case other // ?? var description: String { switch self { case .segue: return "Segue" case .fixed: return "Fixed" case .push: return "Push" case .modal: return "Modal" case .variable: return "Variable" case .redirect: return "Redirect" case .other: return "Other" } } } @objc open class Route: NSObject { /// The name of the route, ie: "reviews" public let name: String? public let type: RoutingType open var userInfo = [String: AnyObject]() open internal(set) var subRoutes = [Route]() // this used to be weak, however due to the nature of how things are registered, // it can't be weak. This creates a *retain loop*, however there is no mechanism // to remove existing route entries (we don't want someone unregistering // someoneelse's route). open internal(set) var parentRoute: Route? /// Action block public let action: RouteActionClosure? public init(_ route: RouteEnum, parentRoute: Route! = nil, action: RouteActionClosure! = nil) { self.name = route.spec.name self.type = route.spec.type self.action = action self.parentRoute = parentRoute } internal init(_ name: String, type: RoutingType, parentRoute: Route! = nil, action: RouteActionClosure! = nil) { self.name = name self.type = type self.action = action self.parentRoute = parentRoute } internal init(type: RoutingType, parentRoute: Route! = nil, action: RouteActionClosure! = nil) { self.name = nil self.type = type self.parentRoute = parentRoute self.action = action } fileprivate weak var staticValue: AnyObject? = nil internal weak var parentRouter: Router? // MARK: - Adding sub routes @discardableResult open func variable(_ action: RouteActionClosure! = nil) -> Route { if route(forType: .variable) != nil { let message = "A variable route already exists on \(String(describing: self.name))!" if isInUnitTest() { exceptionFailure(message) } else { assertionFailure(message) } } let variable = Route(type: .variable, parentRoute: self, action: action) variable.parentRouter = parentRouter subRoutes.append(variable) return variable } @discardableResult open func route(_ route: RouteEnum, action: RouteActionClosure! = nil) -> Route { return self.route(route.spec.name, type: route.spec.type, action: action) } /** Create a subroute based on an existing Route object. This effectively copies the existing route that is passed in, it does not copy any subroutes though. Just name/type/action. */ @discardableResult open func route(_ route: Route) -> Route { if route.type == .variable || self.route(forName: route.name!) != nil { // throw an error let message = "A variable or route with the same name already exists on \(String(describing: self.name))!" if isInUnitTest() { exceptionFailure(message) } else { assertionFailure(message) } } let newRoute = Route(route.name!, type: route.type, parentRoute: self, action: route.action) newRoute.parentRouter = parentRouter subRoutes.append(newRoute) return newRoute } // MARK: - Adding sub routes, for testability only! @discardableResult open func route(_ name: String, type: RoutingType, action: RouteActionClosure! = nil) -> Route { if let existing = self.route(forName: name) { let message = "A route already exists named \(existing.name!)!" if isInUnitTest() { exceptionFailure(message) } else { assertionFailure(message) } } let route = Route(name, type: type, parentRoute: self, action: action) route.parentRouter = parentRouter subRoutes.append(route) return route } // MARK: - Executing Routes /** For testability only! */ @discardableResult internal func execute(_ animated: Bool, variable: String? = nil) -> Any? { var data: AssociatedData? = nil return execute(animated, variable: variable, remainingComponents: [String](), associatedData: &data) } /** Execute the route's action - parameter animated: Determines if the view controller action should be animated. - parameter variable: The variable value extracted from the URL component. - parameter associatedData: Potentially extra data passed in from the outside. */ @discardableResult internal func execute(_ animated: Bool, variable: String?, remainingComponents: [String], associatedData: inout AssociatedData?) -> Any? { // bail out when missing a valid action guard let action = action else { Router.lock.unlock() return nil } var result: Any? = nil var navActionOccurred = false if let navigator = parentRouter?.navigator { if let staticValue = staticValue { _ = action(variable, remainingComponents, &associatedData) result = staticValue if let vc = staticValue as? UIViewController { parentRouter?.navigator?.selectedViewController = vc if let nav = vc as? UINavigationController { if nav.viewControllers.count > 1 { nav.popToRootViewController(animated: animated) navActionOccurred = true } } } } else { result = action(variable, remainingComponents, &associatedData) let navController = navigator.selectedViewController as? UINavigationController let lastVC = navController?.topViewController switch(type) { case .fixed: // do nothing. tab's are handled slightly differently above. // TODO: say some meaningful shit about why this works this way. if let vc = result as? UIViewController { staticValue = vc } case .push: if let vc = result as? UIViewController { navController?.router_pushViewController(vc, animated: animated) navActionOccurred = true } case .modal: if let vc = result as? UIViewController { lastVC?.router_presentViewController(vc, animated: animated, completion: nil) navActionOccurred = true } case .segue: if let segueID = result as? String { lastVC?.router_performSegueWithIdentifier(segueID, sender: self) navActionOccurred = true } case .other, .redirect, .variable: break } } } else { // they don't have a navigator setup, so just run it. result = action(variable, remainingComponents, &associatedData) } // if no navigation action actually happened, unlock so route execution can continue. // otherwise, let the swizzle for viewDidAppear: in Router.swift do the unlock. if navActionOccurred == false { Router.lock.unlock() } return result } // MARK: - Finding Routes /** Get all subroutes of a particular name. - parameter name: The name of the routes to get. */ open func routes(forName name: String) -> [Route] { return subRoutes.filterByName(name) } /** Get the first subroute of a particular name. - parameter name: The name of the route to get. */ open func route(forName name: String) -> Route? { let results = routes(forName: name) if results.count > 0 { return results[0] } return nil } /** Get all subroutes of a particular routing type. - parameter type: The routing type of the routes to get. */ open func routes(forType type: RoutingType) -> [Route] { return subRoutes.filterByType(type) } /** Get the first subroute of a particular routing type. - parameter type: The routing type of the routes to get. */ open func route(forType type: RoutingType) -> Route? { let results = routes(forType: type) if results.count > 0 { return results[0] } return nil } /** Get all subroutes that match an array of components. - parameter components: The array of component strings to match against. */ internal func routes(forComponents components: [String]) -> [Route] { var results = [Route]() var currentRoute = self for i in 0..<components.count { let component = components[i] if let route = currentRoute.route(forName: component) { results.append(route) currentRoute = route } else if let variableRoute = currentRoute.route(forType: .variable) { // it IS a variable. results.append(variableRoute) currentRoute = variableRoute } } return results } } extension Sequence where Iterator.Element : Route { /** Filter a collection of Route objects by name. - parameter name: The name of the routes to filter by. */ public func filterByName(_ name: String) -> [Route] { return filter { $0.name == name } } /** Filter a collection of Route objects by routing type. - parameter type: The routing type of the routes to filter by. */ public func filterByType(_ type: RoutingType) -> [Route] { return filter { $0.type == type } } }
mit
7ed1ac6e0923ceeba3c0447c9ac46a27
32.993846
161
0.568972
4.999095
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Services/Service.LockMechanism.swift
1
1093
import Foundation extension Service { open class LockMechanism: Service { public init(characteristics: [AnyCharacteristic] = []) { var unwrapped = characteristics.map { $0.wrapped } lockCurrentState = getOrCreateAppend( type: .lockCurrentState, characteristics: &unwrapped, generator: { PredefinedCharacteristic.lockCurrentState() }) lockTargetState = getOrCreateAppend( type: .lockTargetState, characteristics: &unwrapped, generator: { PredefinedCharacteristic.lockTargetState() }) name = get(type: .name, characteristics: unwrapped) super.init(type: .lockMechanism, characteristics: unwrapped) } // MARK: - Required Characteristics public let lockCurrentState: GenericCharacteristic<Enums.LockCurrentState> public let lockTargetState: GenericCharacteristic<Enums.LockTargetState> // MARK: - Optional Characteristics public let name: GenericCharacteristic<String>? } }
mit
54239549ac7e8ec8a80ee08e258aa212
41.038462
82
0.645014
5.783069
false
false
false
false
Farteen/Spring
Spring/Misc.swift
1
7492
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public extension String { public var length: Int { return countElements(self) } public func toURL() -> NSURL? { return NSURL(string: self) } } public func htmlToAttributedString(text: String) -> NSAttributedString! { let htmlData = text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) let htmlString = NSAttributedString(data: htmlData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil, error: nil) return htmlString } public func degreesToRadians(degrees: CGFloat) -> CGFloat { return degrees * CGFloat(M_PI / 180) } public func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } public func imageFromURL(URL: String) -> UIImage { let url = NSURL(string: URL) let data = NSData(contentsOfURL: url!) return UIImage(data: data!)! } public extension UIColor { convenience init(hex: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 var hex: String = hex if hex.hasPrefix("#") { let index = advance(hex.startIndex, 1) hex = hex.substringFromIndex(index) } let scanner = NSScanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexLongLong(&hexValue) { switch (countElements(hex)) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 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 default: print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8") } } else { println("Scan hex error") } self.init(red:red, green:green, blue:blue, alpha:alpha) } } public func rgbaToUIColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIColor { return UIColor(red: red, green: green, blue: blue, alpha: alpha) } public func UIColorFromRGB(rgbValue: UInt) -> UIColor { return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } public func stringFromDate(date: NSDate, format: String) -> String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = format return dateFormatter.stringFromDate(date) } public func dateFromString(date: String, format: String) -> NSDate { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = format return dateFormatter.dateFromString(date)! } public func randomStringWithLength (len : Int) -> NSString { let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" var randomString : NSMutableString = NSMutableString(capacity: len) for (var i=0; i < len; i++){ var length = UInt32 (letters.length) var rand = arc4random_uniform(length) randomString.appendFormat("%C", letters.characterAtIndex(Int(rand))) } return randomString } public func timeAgoSinceDate(date:NSDate, numericDates:Bool) -> String { let calendar = NSCalendar.currentCalendar() let unitFlags = NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitWeekOfYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitSecond let now = NSDate() let earliest = now.earlierDate(date) let latest = now.laterDate(date) let components:NSDateComponents = calendar.components(unitFlags, fromDate: earliest, toDate: latest, options: nil) if (components.year >= 2) { return "\(components.year)y" } else if (components.year >= 1){ if (numericDates){ return "1y" } else { return "1y" } } else if (components.month >= 2) { return "\(components.month)" } else if (components.month >= 1){ if (numericDates){ return "1M" } else { return "1M" } } else if (components.weekOfYear >= 2) { return "\(components.weekOfYear)w" } else if (components.weekOfYear >= 1){ if (numericDates){ return "1w" } else { return "1w" } } else if (components.day >= 2) { return "\(components.day)d" } else if (components.day >= 1){ if (numericDates){ return "1d" } else { return "1d" } } else if (components.hour >= 2) { return "\(components.hour)h" } else if (components.hour >= 1){ if (numericDates){ return "1h" } else { return "1h" } } else if (components.minute >= 2) { return "\(components.minute)m" } else if (components.minute >= 1){ if (numericDates){ return "1m" } else { return "1m" } } else if (components.second >= 3) { return "\(components.second)s" } else { return "now" } }
mit
504a9616202f6f309d222498e92cd7f8
35.198068
265
0.606113
4.264087
false
false
false
false
camdenfullmer/UnsplashSwift
Example/Source/ImageCell.swift
1
2643
// ImageCell.swift // // Copyright (c) 2016 Camden Fullmer (http://camdenfullmer.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 Alamofire import AlamofireImage class ImageCell: UICollectionViewCell { class var ReuseIdentifier: String { return "com.unsplash.identifier.\(self.dynamicType)" } let imageView: UIImageView // MARK: - Initialization override init(frame: CGRect) { imageView = { let imageView = UIImageView(frame: frame) imageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] imageView.contentMode = .Center imageView.clipsToBounds = true return imageView }() super.init(frame: frame) contentView.addSubview(imageView) imageView.frame = contentView.bounds } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Lifecycle Methods func configureCellWithURLString(URLString: String) { let size = imageView.frame.size imageView.af_setImageWithURL( NSURL(string: URLString)!, placeholderImage: nil, filter: AspectScaledToFillSizeFilter.init(size: size), imageTransition: .CrossDissolve(0.2) ) } override func prepareForReuse() { super.prepareForReuse() imageView.af_cancelImageRequest() imageView.layer.removeAllAnimations() imageView.image = nil } }
mit
d08d2909ff8c60105349edf64e515581
33.776316
94
0.67045
5.132039
false
false
false
false
lenssss/whereAmI
Whereami/Controller/Chat/ChatSelectFriendViewController.swift
1
6702
// // ChatSelectFriendViewController.swift // Whereami // // Created by A on 16/5/11. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit class ChatSelectFriendViewController: UIViewController,UITableViewDelegate,UITableViewDataSource,UISearchControllerDelegate,UISearchBarDelegate { var tableView:UITableView? = nil // private var currentConversations:[ConversationModel]? = nil var searchResultVC:ChatSelectFriendSearchResultViewController? = nil var searchController:UISearchController? = nil var currentFriends:[FriendsModel]? = nil var newConversationHasDone:NewConversation? = nil override func viewDidLoad() { super.viewDidLoad() self.title = NSLocalizedString("chooseOpponents",tableName:"Localizable", comment: "") self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName:UIFont.customFontWithStyle("Bold", size:18.0)!,NSForegroundColorAttributeName:UIColor.whiteColor()] self.setConfig() self.setupUI() LNotificationCenter().rac_addObserverForName(UIKeyboardWillHideNotification, object: nil).subscribeNext { (notification) -> Void in self.searchController?.active = false } LNotificationCenter().rac_addObserverForName(KNotificationDismissSearchView, object: nil).subscribeNext { (notification) -> Void in let id = notification.object! as! String self.runInMainQueue({ let personalVC = TourRecordsViewController() personalVC.userId = id personalVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(personalVC, animated: true) }) } } func setupUI() { let backBtn = TheBackBarButton.initWithAction({ let viewControllers = self.navigationController?.viewControllers let index = (viewControllers?.count)! - 2 let viewController = viewControllers![index] self.navigationController?.popToViewController(viewController, animated: true) }) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn) self.tableView = UITableView() self.view.addSubview(self.tableView!) self.tableView?.delegate = self self.tableView?.dataSource = self self.tableView?.tableFooterView = UIView() self.tableView?.registerClass(ContactItemTableViewCell.self, forCellReuseIdentifier: "ContactItemTableViewCell") searchResultVC = ChatSelectFriendSearchResultViewController() searchController = UISearchController(searchResultsController: searchResultVC) searchController?.searchResultsUpdater = searchResultVC searchController?.delegate = self searchController?.searchBar.sizeToFit() searchController?.active = true searchController?.searchBar.delegate = self searchResultVC!.newConversationHasDone = { (conversion:AVIMConversation,hostUser:ChattingUserModel,guestUser:ChattingUserModel) in self.push2ConversationVC(conversion, hostUser: hostUser, guestUser: guestUser) } self.tableView?.autoPinEdgesToSuperviewEdgesWithInsets(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)) self.tableView?.tableHeaderView = searchController?.searchBar } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.currentFriends = CoreDataManager.sharedInstance.fetchAllFriends() self.tableView?.reloadData() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if currentFriends != nil { return currentFriends!.count } return 0 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 70.0; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:ContactItemTableViewCell = tableView.dequeueReusableCellWithIdentifier("ContactItemTableViewCell", forIndexPath: indexPath) as! ContactItemTableViewCell let friendModel = currentFriends![indexPath.row] let avatarUrl = friendModel.headPortrait != nil ? friendModel.headPortrait : "" cell.avatar?.kf_setImageWithURL(NSURL(string:avatarUrl!)!, placeholderImage: UIImage(named: "avator.png"), optionsInfo: nil, progressBlock: nil, completionHandler: nil) cell.chatName?.text = friendModel.nickname! cell.addButton?.enabled = false let userModel = CoreDataManager.sharedInstance.fetchUserById(friendModel.friendId!) cell.location?.text = userModel?.countryName return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let friendModel:FriendsModel = self.currentFriends![indexPath.row] let currentUser = UserModel.getCurrentUser() let guestUser = ChattingUserModel() let hostUser = ChattingUserModel() guestUser.accountId = friendModel.friendId guestUser.headPortrait = friendModel.headPortrait guestUser.nickname = friendModel.nickname hostUser.accountId = currentUser?.id hostUser.headPortrait = currentUser?.headPortraitUrl hostUser.nickname = currentUser?.nickname LeanCloudManager.sharedInstance.createConversitionWithClientIds(guestUser.accountId!, clientIds: [guestUser.accountId!]) { (succed, conversion) in if(succed) { CoreDataConversationManager.sharedInstance.increaseOrCreateUnreadCountByConversation( conversion!, lastMsg: "", msgType: kAVIMMessageMediaTypeText) self.push2ConversationVC(conversion!, hostUser: hostUser, guestUser: guestUser) } } } func push2ConversationVC(conversion:AVIMConversation,hostUser:ChattingUserModel,guestUser:ChattingUserModel) { let conversationVC = ConversationViewController() conversationVC.conversation = conversion conversationVC.hostModel = hostUser conversationVC.guestModel = guestUser conversationVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(conversationVC, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
1ccd645093449716f66186a976df9697
44.263514
191
0.696223
5.917845
false
false
false
false
BasThomas/MacOSX
ImageTiling/ImageTiling/TiledImageView.swift
1
1309
// // TiledImageView.swift // ImageTiling // // Created by Bas Broek on 04/05/15. // Copyright (c) 2015 Bas Broek. All rights reserved. // import Cocoa @IBDesignable class TiledImageView: NSView { @IBInspectable var image: NSImage? let columnCount = 5 let rowCount = 5 override var intrinsicContentSize: NSSize { let furthestFrame = self.frameForImageAtLogicalX(self.columnCount - 1, y: self.rowCount - 1) return NSSize(width: furthestFrame.maxX, height: furthestFrame.maxY) } override func drawRect(dirtyRect: NSRect) { super.drawRect(dirtyRect) if let image = image { for x in 0..<self.columnCount { for y in 0..<self.rowCount { let frame = self.frameForImageAtLogicalX(x, y: y) image.drawInRect(frame) } } } } // MARK: - Drawing func frameForImageAtLogicalX(logicalX: Int, y logicalY: Int) -> CGRect { let spacing = 10 let width = 100 let height = 100 let x = (spacing + width) * logicalX let y = (spacing + height) * logicalY return CGRect(x: x, y: y, width: width, height: height) } }
mit
dda40dce9bfb5c4f5b36d7fdaf70bd64
24.192308
100
0.553094
4.195513
false
false
false
false
ayanna92/ayannacolden-programmeerproject
programmeerproject/MessagesController.swift
1
11223
// // MessagesController.swift // programmeerproject // // Created by Ayanna Colden on 17/01/2017. // Copyright © 2017 Ayanna Colden. All rights reserved. // import UIKit import Firebase // Source: https://www.letsbuildthatapp.com/course_video?id=402 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 MessagesController: UITableViewController { let cellId = "cellId" override func viewDidLoad() { super.viewDidLoad() self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "menu_icon") , style: .plain, target: self.revealViewController(), action: #selector(SWRevealViewController.revealToggle(_:))) self.navigationItem.leftBarButtonItem?.tintColor = UIColor.black self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) let image = UIImage(named: "new_message_icon") self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(handleNewMessage)) self.navigationItem.rightBarButtonItem?.tintColor = UIColor.black self.tableView.backgroundColor = UIColor.groupTableViewBackground checkIfUserIsLoggedIn() tableView.register(UserMessageCell.self, forCellReuseIdentifier: cellId) tableView.allowsMultipleSelectionDuringEditing = true } var messages = [Message]() var messagesDictionary = [String: Message]() func observeUserMessages() { guard let uid = FIRAuth.auth()?.currentUser?.uid else { return } let ref = FIRDatabase.database().reference().child("user-messages").child(uid) ref.observe(.childAdded, with: { (snapshot) in let userId = snapshot.key FIRDatabase.database().reference().child("user-messages").child(uid).child(userId).observe(.childAdded, with: { (snapshot) in let messageId = snapshot.key self.fetchMessageWithMessageId(messageId) }, withCancel: nil) }, withCancel: nil) ref.observe(.childRemoved, with: { (snapshot) in self.messagesDictionary.removeValue(forKey: snapshot.key) self.attemptReloadOfTable() }, withCancel: nil) } fileprivate func fetchMessageWithMessageId(_ messageId: String) { let messagesReference = FIRDatabase.database().reference().child("messages").child(messageId) messagesReference.observeSingleEvent(of: .value, with: { (snapshot) in if let dictionary = snapshot.value as? [String: AnyObject] { let message = Message(dictionary: dictionary) if let chatPartnerId = message.chatPartnerId() { self.messagesDictionary[chatPartnerId] = message } self.attemptReloadOfTable() } }, withCancel: nil) } fileprivate func attemptReloadOfTable() { self.timer?.invalidate() self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.handleReloadTable), userInfo: nil, repeats: false) } var timer: Timer? func handleReloadTable() { self.messages = Array(self.messagesDictionary.values) self.messages.sort(by: { (message1, message2) -> Bool in return message1.timestamp?.int32Value > message2.timestamp?.int32Value }) DispatchQueue.main.async(execute: { self.tableView.reloadData() }) } func handleNewMessage() { let newMessageController = NewMessagesController() newMessageController.messagesController = self let navController = UINavigationController(rootViewController: newMessageController) present(navController, animated: true, completion: nil) } func checkIfUserIsLoggedIn() { if FIRAuth.auth()?.currentUser?.uid == nil { perform(#selector(handleLogout), with: nil, afterDelay: 0) } else { fetchUserAndSetupNavBarTitle() } } func showChatControllerForUser(_ user: UserMessages) { let chatLogController = ChatController(collectionViewLayout: UICollectionViewFlowLayout()) chatLogController.user = user navigationController?.pushViewController(chatLogController, animated: true) } func handleLogout() { do { try FIRAuth.auth()?.signOut() } catch let logoutError { print(logoutError) } let loginController = LoginViewController() loginController.messagesController = self let naviController = UINavigationController(rootViewController: loginController) present(naviController, animated: true, completion: nil) } // MARK: Navigation Bar Functions. func fetchUserAndSetupNavBarTitle() { guard let uid = FIRAuth.auth()?.currentUser?.uid else { return } FIRDatabase.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in if let dictionary = snapshot.value as? [String: AnyObject] { let user = UserMessages() user.setValuesForKeys(dictionary) self.setupNavBarWithUser(user) } }, withCancel: nil) } func setupNavBarWithUser(_ user: UserMessages) { messages.removeAll() messagesDictionary.removeAll() tableView.reloadData() observeUserMessages() let titleView = UIView() titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40) // titleView.backgroundColor = UIColor.redColor() let containerView = UIView() containerView.translatesAutoresizingMaskIntoConstraints = false titleView.addSubview(containerView) let profileImageView = UIImageView() profileImageView.translatesAutoresizingMaskIntoConstraints = false profileImageView.contentMode = .scaleAspectFill profileImageView.layer.cornerRadius = 20 profileImageView.clipsToBounds = true if let profileImageUrl = user.urlToImage { profileImageView.loadImageUsingCacheWithUrlString(profileImageUrl) } containerView.addSubview(profileImageView) //ios 9 constraint anchors //need x,y,width,height anchors profileImageView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true profileImageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true profileImageView.widthAnchor.constraint(equalToConstant: 40).isActive = true profileImageView.heightAnchor.constraint(equalToConstant: 40).isActive = true let nameLabel = UILabel() containerView.addSubview(nameLabel) nameLabel.text = user.fullname nameLabel.translatesAutoresizingMaskIntoConstraints = false //need x,y,width,height anchors nameLabel.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 8).isActive = true nameLabel.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor).isActive = true nameLabel.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true nameLabel.heightAnchor.constraint(equalTo: profileImageView.heightAnchor).isActive = true containerView.centerXAnchor.constraint(equalTo: titleView.centerXAnchor).isActive = true containerView.centerYAnchor.constraint(equalTo: titleView.centerYAnchor).isActive = true self.navigationItem.titleView = titleView // titleView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(showChatController))) } // MARK: Tableview. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { guard let uid = FIRAuth.auth()?.currentUser?.uid else { return } let message = self.messages[(indexPath as NSIndexPath).row] if let chatPartnerId = message.chatPartnerId() { FIRDatabase.database().reference().child("user-messages").child(uid).child(chatPartnerId).removeValue(completionBlock: { (error, ref) in if error != nil { print("Failed to delete message:", error!) return } self.messagesDictionary.removeValue(forKey: chatPartnerId) self.attemptReloadOfTable() }) } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! UserMessageCell let message = messages[(indexPath as NSIndexPath).row] cell.message = message return cell } override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.backgroundColor = UIColor.clear } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 72 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let message = messages[(indexPath as NSIndexPath).row] guard let chatPartnerId = message.chatPartnerId() else { return } let ref = FIRDatabase.database().reference().child("users").child(chatPartnerId) ref.observeSingleEvent(of: .value, with: { (snapshot) in guard let dictionary = snapshot.value as? [String: AnyObject] else { return } let user = UserMessages() user.uid = chatPartnerId user.setValuesForKeys(dictionary) self.showChatControllerForUser(user) }, withCancel: nil) } }
apache-2.0
c72bc5f52bfecb5deaf7ee6f09dfce54
34.853035
212
0.621458
5.544466
false
false
false
false
Speicher210/wingu-sdk-ios-demoapp
Example/Pods/RSBarcodes_Swift/Source/RSUnifiedCodeGenerator.swift
1
4210
// // RSUnifiedCodeGenerator.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/10/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import Foundation import UIKit import AVFoundation open class RSUnifiedCodeGenerator: RSCodeGenerator { open var isBuiltInCode128GeneratorSelected = false open var fillColor: UIColor = UIColor.white open var strokeColor: UIColor = UIColor.black open class var shared: RSUnifiedCodeGenerator { return UnifiedCodeGeneratorSharedInstance } // MARK: RSCodeGenerator open func isValid(_ contents: String) -> Bool { print("Use RSUnifiedCodeValidator.shared.isValid(contents:String, machineReadableCodeObjectType: String) instead") return false } open func generateCode(_ contents: String, inputCorrectionLevel: InputCorrectionLevel, machineReadableCodeObjectType: String) -> UIImage? { var codeGenerator: RSCodeGenerator? switch machineReadableCodeObjectType { case AVMetadataObjectTypeQRCode, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeAztecCode: return RSAbstractCodeGenerator.generateCode(contents, inputCorrectionLevel: inputCorrectionLevel, filterName: RSAbstractCodeGenerator.filterName(machineReadableCodeObjectType)) case AVMetadataObjectTypeCode39Code: codeGenerator = RSCode39Generator() case AVMetadataObjectTypeCode39Mod43Code: codeGenerator = RSCode39Mod43Generator() case AVMetadataObjectTypeEAN8Code: codeGenerator = RSEAN8Generator() case AVMetadataObjectTypeEAN13Code: codeGenerator = RSEAN13Generator() case AVMetadataObjectTypeInterleaved2of5Code: codeGenerator = RSITFGenerator() case AVMetadataObjectTypeITF14Code: codeGenerator = RSITF14Generator() case AVMetadataObjectTypeUPCECode: codeGenerator = RSUPCEGenerator() case AVMetadataObjectTypeCode93Code: codeGenerator = RSCode93Generator() // iOS 8 included, but my implementation's performance is better :) case AVMetadataObjectTypeCode128Code: if self.isBuiltInCode128GeneratorSelected { return RSAbstractCodeGenerator.generateCode(contents, inputCorrectionLevel: inputCorrectionLevel, filterName: RSAbstractCodeGenerator.filterName(machineReadableCodeObjectType)) } else { codeGenerator = RSCode128Generator() } case AVMetadataObjectTypeDataMatrixCode: codeGenerator = RSCodeDataMatrixGenerator() case RSBarcodesTypeISBN13Code: codeGenerator = RSISBN13Generator() case RSBarcodesTypeISSN13Code: codeGenerator = RSISSN13Generator() case RSBarcodesTypeExtendedCode39Code: codeGenerator = RSExtendedCode39Generator() default: print("No code generator selected.") } if codeGenerator != nil { codeGenerator!.fillColor = self.fillColor codeGenerator!.strokeColor = self.strokeColor return codeGenerator!.generateCode(contents, inputCorrectionLevel: inputCorrectionLevel, machineReadableCodeObjectType: machineReadableCodeObjectType) } else { return nil } } open func generateCode(_ contents: String, machineReadableCodeObjectType: String) -> UIImage? { return self.generateCode(contents, inputCorrectionLevel: .Medium, machineReadableCodeObjectType: machineReadableCodeObjectType) } open func generateCode(_ machineReadableCodeObject: AVMetadataMachineReadableCodeObject, inputCorrectionLevel: InputCorrectionLevel) -> UIImage? { return self.generateCode(machineReadableCodeObject.stringValue, inputCorrectionLevel: inputCorrectionLevel, machineReadableCodeObjectType: machineReadableCodeObject.type) } open func generateCode(_ machineReadableCodeObject: AVMetadataMachineReadableCodeObject) -> UIImage? { return self.generateCode(machineReadableCodeObject, inputCorrectionLevel: .Medium) } } let UnifiedCodeGeneratorSharedInstance = RSUnifiedCodeGenerator()
apache-2.0
36308f35ecc030711871860e2fd8ba37
44.76087
192
0.725653
6.629921
false
false
false
false
googlemaps/maps-sdk-for-ios-samples
snippets/MapsSnippets/MapsSnippets/Swift/MapWithMarkerViewController.swift
1
1123
// // MapWithMarkerViewController.swift // MapsSnippets // // Created by Chris Arriola on 9/14/20. // Copyright © 2020 Google. All rights reserved. // import UIKit import GoogleMaps class MapWithMarkerViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // [START maps_ios_map_with_marker_create_map] // Create a GMSCameraPosition that tells the map to display the // coordinate -33.86,151.20 at zoom level 6. let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0) let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) view = mapView // [END maps_ios_map_with_marker_create_map] // [START maps_ios_map_with_marker_add_marker] // Creates a marker in the center of the map. let marker = GMSMarker() marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20) marker.title = "Sydney" marker.snippet = "Australia" marker.map = mapView // [END maps_ios_map_with_marker_add_marker] } }
apache-2.0
746321e4e36b54da3807fad4afc70170
33
97
0.656863
3.842466
false
false
false
false
mattdaw/SwiftBoard
SwiftBoard/ViewModels/ListViewModel.swift
1
1808
// // ListViewModel.swift // SwiftBoard // // Created by Matt Daw on 2014-11-17. // Copyright (c) 2014 Matt Daw. All rights reserved. // import Foundation protocol ListViewModelDelegate: class { func listViewModelItemMoved(fromIndex: Int, toIndex: Int) func listViewModelItemAddedAtIndex(index: Int) func listViewModelItemRemovedAtIndex(index: Int) } class ListViewModel { private var viewModels: [ItemViewModel] weak var listViewModelDelegate: ListViewModelDelegate? init(viewModels initViewModels:[ItemViewModel]) { viewModels = initViewModels for itemViewModel in viewModels { itemViewModel.parentListViewModel = self } } func numberOfItems() -> Int { return viewModels.count } func itemAtIndex(index: Int) -> ItemViewModel { return viewModels[index] } func indexOfItem(item: ItemViewModel) -> Int? { for (index, compareItem) in enumerate(viewModels) { if item === compareItem { return index } } return nil } func moveItemAtIndex(fromIndex: Int, toIndex: Int) { var item: ItemViewModel = viewModels[fromIndex] viewModels.removeAtIndex(fromIndex) viewModels.insert(item, atIndex: toIndex) listViewModelDelegate?.listViewModelItemMoved(fromIndex, toIndex: toIndex) } func removeItemAtIndex(index: Int) { viewModels.removeAtIndex(index) listViewModelDelegate?.listViewModelItemRemovedAtIndex(index) } func appendItem(itemViewModel: ItemViewModel) { let index = viewModels.count viewModels.append(itemViewModel) listViewModelDelegate?.listViewModelItemAddedAtIndex(index) } }
mit
0dd7f60428f6d5ef55a090c4db4985b7
26.830769
82
0.655973
4.939891
false
false
false
false
13983441921/TextField-InputView
UITextField+InputView/MulSelVC.swift
1
1141
// // MulSelVC.swift // TextField+InputView // // Created by 成林 on 15/8/31. // Copyright (c) 2015年 冯成林. All rights reserved. // import UIKit class Service: MulSelTFDataModelProtocol { var title: String! var isChecked: Bool! var isRequired: Bool! init(title: String,isChecked: Bool,isRequired: Bool){ self.title = title self.isChecked = isChecked self.isRequired=isRequired } } class MulSelVC: UIViewController { @IBOutlet weak var tf: MulSelTF! override func viewDidLoad() { super.viewDidLoad() let s1 = Service(title: "翻译", isChecked: true,isRequired:true) let s2 = Service(title: "司机", isChecked: false,isRequired:false) let s3 = Service(title: "公关", isChecked: false,isRequired:false) let s4 = Service(title: "导游", isChecked: false,isRequired:false) let s5 = Service(title: "商务", isChecked: false,isRequired:false) tf.addMulSelWithModels([s1,s2,s3,s4,s5]) tf.doneBtnClickClosure = {(all,checked) in } } }
mit
176ef70b5186242a0cc1585dadaaef56
23.644444
72
0.609558
3.734007
false
false
false
false
DasHutch/minecraft-castle-challenge
app/_src/BaseTableViewController.swift
1
1419
// // BaseTableViewController.swift // MC Castle Challenge // // Created by Gregory Hutchinson on 9/24/15. // Copyright © 2015 Gregory Hutchinson. All rights reserved. // import UIKit class BaseTableViewController: ContentSizeChangeObservingTableViewController {} // MARK: - UITableViewDelegate extension BaseTableViewController { override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { fixCellSeparatorInsets(cell) } //MARK: Helpers /** Fixes UITableViewCell Separator Inset will set `separatorInset` & `layoutMargins` to `UIEdgeInsetsZero` and turn off `preservesSuperviewLayoutMargins` */ private func fixCellSeparatorInsets(cell: UITableViewCell) { let separatorInsetSelector = Selector("separatorInset") if cell.respondsToSelector(separatorInsetSelector) { cell.separatorInset = UIEdgeInsetsZero } let preservesSuperviewLayoutMarginsSelector = Selector("preservesSuperviewLayoutMargins") if cell.respondsToSelector(preservesSuperviewLayoutMarginsSelector) { cell.preservesSuperviewLayoutMargins = false } let layoutMarginsSelector = Selector("layoutMargins") if cell.respondsToSelector(layoutMarginsSelector) { cell.layoutMargins = UIEdgeInsetsZero } } }
gpl-2.0
907c56784f6ac8d0923ffc618057072d
32.761905
134
0.723554
5.908333
false
false
false
false
longsirhero/DinDinShop
DinDinShopDemo/Pods/ImageViewer/ImageViewer/Source/VideoView.swift
1
2297
// // VideoView.swift // ImageViewer // // Created by Kristian Angyal on 25/07/2016. // Copyright © 2016 MailOnline. All rights reserved. // import UIKit import AVFoundation class VideoView: UIView { let previewImageView = UIImageView() var image: UIImage? { didSet { previewImageView.image = image } } var player: AVPlayer? { willSet { if newValue == nil { player?.removeObserver(self, forKeyPath: "status") player?.removeObserver(self, forKeyPath: "rate") } } didSet { if let player = self.player, let videoLayer = self.layer as? AVPlayerLayer { videoLayer.player = player videoLayer.videoGravity = AVLayerVideoGravityResizeAspect player.addObserver(self, forKeyPath: "status", options: NSKeyValueObservingOptions.new, context: nil) player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil) } } } override class var layerClass : AnyClass { return AVPlayerLayer.self } convenience init() { self.init(frame: CGRect.zero) } override init(frame: CGRect) { super.init(frame: frame) self.addSubview(previewImageView) previewImageView.contentMode = .scaleAspectFill previewImageView.autoresizingMask = [.flexibleWidth, .flexibleHeight] previewImageView.clipsToBounds = true } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { player?.removeObserver(self, forKeyPath: "status") player?.removeObserver(self, forKeyPath: "rate") } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let status = self.player?.status, let rate = self.player?.rate { if status == .readyToPlay && rate != 0 { UIView.animate(withDuration: 0.3, animations: { [weak self] in if let strongSelf = self { strongSelf.previewImageView.alpha = 0 } }) } } } }
mit
a9fcd7da7ceb844dd30e8782cd58f2c3
26.011765
151
0.595383
5.079646
false
false
false
false
jaronoff97/listmkr_backend
Sources/App/main.swift
2
6168
import Vapor import HTTP /** Droplets are service containers that make accessing all of Vapor's features easy. Just call `drop.serve()` to serve your application or `drop.client()` to create a client for request data from other servers. */ let drop = Droplet() /** Vapor configuration files are located in the root directory of the project under `/Config`. `.json` files in subfolders of Config override other JSON files based on the current server environment. Read the docs to learn more */ let _ = drop.config["app", "key"]?.string ?? "" /** This first route will return the welcome.html view to any request to the root directory of the website. Views referenced with `app.view` are by default assumed to live in <workDir>/Resources/Views/ You can override the working directory by passing --workDir to the application upon execution. */ drop.get("/") { request in return try drop.view.make("welcome.html") } /** Return JSON requests easy by wrapping any JSON data type (String, Int, Dict, etc) in JSON() and returning it. Types can be made convertible to JSON by conforming to JsonRepresentable. The User model included in this example demonstrates this. By conforming to JsonRepresentable, you can pass the data structure into any JSON data as if it were a native JSON data type. */ drop.get("json") { request in return try JSON(node: [ "number": 123, "string": "test", "array": try JSON(node: [ 0, 1, 2, 3 ]), "dict": try JSON(node: [ "name": "Vapor", "lang": "Swift" ]) ]) } /** This route shows how to access request data. POST to this route with either JSON or Form URL-Encoded data with a structure like: { "users" [ { "name": "Test" } ] } You can also access different types of request.data manually: - Query: request.data.query - JSON: request.data.json - Form URL-Encoded: request.data.formEncoded - MultiPart: request.data.multipart */ drop.get("data", Int.self) { request, int in return try JSON(node: [ "int": int, "name": request.data["name"]?.string ?? "no name" ]) } /** Here's an example of using type-safe routing to ensure only requests to "posts/<some-integer>" will be handled. String is the most general and will match any request to "posts/<some-string>". To make your data structure work with type-safe routing, make it StringInitializable. The User model included in this example is StringInitializable. */ drop.get("posts", Int.self) { request, postId in return "Requesting post with ID \(postId)" } /** This will set up the appropriate GET, PUT, and POST routes for basic CRUD operations. Check out the UserController in App/Controllers to see more. Controllers are also type-safe, with their types being defined by which StringInitializable class they choose to receive as parameters to their functions. */ let users = UserController(droplet: drop) drop.resource("users", users) drop.get("leaf") { request in return try drop.view.make("template", [ "greeting": "Hello, world!" ]) } /** A custom validator definining what constitutes a valid name. Here it is defined as an alphanumeric string that is between 5 and 20 characters. */ class Name: ValidationSuite { static func validate(input value: String) throws { let evaluation = OnlyAlphanumeric.self && Count.min(5) && Count.max(20) try evaluation.validate(input: value) } } /** By using `Valid<>` properties, the employee class ensures only valid data will be stored. */ class Employee { var email: Valid<Email> var name: Valid<Name> init(request: Request) throws { email = try request.data["email"].validated() name = try request.data["name"].validated() } } /** Allows any instance of employee to be returned as Json */ extension Employee: JSONRepresentable { func makeJSON() throws -> JSON { return try JSON(node: [ "email": email.value, "name": name.value ]) } } // Temporarily unavailable //drop.any("validation") { request in // return try Employee(request: request) //} /** This simple plaintext response is useful when benchmarking Vapor. */ drop.get("plaintext") { request in return "Hello, World!" } /** Vapor automatically handles setting and retreiving sessions. Simply add data to the session variable and–if the user has cookies enabled–the data will persist with each request. */ drop.get("session") { request in let json = try JSON(node: [ "session.data": "\(request.session().data["name"])", "request.cookies": "\(request.cookies)", "instructions": "Refresh to see cookie and session get set." ]) var response = try Response(status: .ok, json: json) try request.session().data["name"] = "Vapor" response.cookies["test"] = "123" return response } /** Add Localization to your app by creating a `Localization` folder in the root of your project. /Localization |- en.json |- es.json |_ default.json The first parameter to `app.localization` is the language code. */ drop.get("localization", String.self) { request, lang in return try JSON(node: [ "title": drop.localization[lang, "welcome", "title"], "body": drop.localization[lang, "welcome", "body"] ]) } /** Middleware is a great place to filter and modifying incoming requests and outgoing responses. Check out the middleware in App/Middleware. You can also add middleware to a single route by calling the routes inside of `app.middleware(MiddlewareType) { app.get() { ... } }` */ drop.middleware.append(SampleMiddleware()) let port = drop.config["app", "port"]?.int ?? 80 // Print what link to visit for default port drop.run()
mit
9da66fb9b42f6ac3614f0cddf07d6496
24.471074
68
0.642116
4.15644
false
false
false
false
practicalswift/swift
test/Driver/actions.swift
4
9296
// RUN: %empty-directory(%t) // XFAIL: freebsd, linux // RUN: %swiftc_driver -driver-print-actions %s 2>&1 | %FileCheck %s -check-prefix=BASIC // BASIC: 0: input, "{{.*}}actions.swift", swift // BASIC: 1: compile, {0}, object // BASIC: 2: link, {1}, image // RUN: %swiftc_driver -driver-print-actions -c %s 2>&1 | %FileCheck %s -check-prefix=BASICC // BASICC: 0: input, "{{.*}}actions.swift", swift // BASICC: 1: compile, {0}, object // RUN: %swiftc_driver -driver-print-actions -dump-ast %s 2>&1 | %FileCheck %s -check-prefix=BASICAST // BASICAST: 0: input, "{{.*}}actions.swift", swift // BASICAST: 1: compile, {0}, ast-dump // RUN: %swiftc_driver -driver-print-actions -emit-sil %s 2>&1 | %FileCheck %s -check-prefix=BASICSIL // BASICSIL: 0: input, "{{.*}}actions.swift", swift // BASICSIL: 1: compile, {0}, sil // RUN: %swiftc_driver -driver-print-actions -emit-silgen %s 2>&1 | %FileCheck %s -check-prefix=BASICSILGEN // BASICSILGEN: 0: input, "{{.*}}actions.swift", swift // BASICSILGEN: 1: compile, {0}, raw-sil // RUN: %swiftc_driver -driver-print-actions -S %s 2>&1 | %FileCheck %s -check-prefix=BASICASM // BASICASM: 0: input, "{{.*}}actions.swift", swift // BASICASM: 1: compile, {0}, assembly // RUN: %swiftc_driver -driver-print-actions -emit-module %s 2>&1 | %FileCheck %s -check-prefix=BASICMODULE // BASICMODULE: 0: input, "{{.*}}actions.swift", swift // BASICMODULE: 1: compile, {0}, swiftmodule // BASICMODULE: 2: merge-module, {1}, swiftmodule // RUN: touch %t/a.swiftmodule // RUN: %swiftc_driver -driver-print-actions -emit-module -module-name foo %s %t/a.swiftmodule 2>&1 | %FileCheck %s -check-prefix=SWIFTMODULE-INPUT // SWIFTMODULE-INPUT: 0: input, "{{.*}}actions.swift", swift // SWIFTMODULE-INPUT: 1: compile, {0}, swiftmodule // SWIFTMODULE-INPUT: 2: input, "{{.*}}a.swiftmodule", swift // SWIFTMODULE-INPUT: 3: merge-module, {1, 2}, swiftmodule // RUN: %swiftc_driver -driver-print-actions -g -emit-module -module-name foo %s %t/a.swiftmodule 2>&1 | %FileCheck %s -check-prefix=SWIFTMODULE-INPUT // SWIFTMODULE-DEBUG-INPUT: 0: input, "{{.*}}actions.swift", swift // SWIFTMODULE-DEBUG-INPUT: 1: compile, {0}, swiftmodule // SWIFTMODULE-DEBUG-INPUT: 2: input, "{{.*}}a.swiftmodule", swift // SWIFTMODULE-DEBUG-INPUT: 3: merge-module, {1, 2}, swiftmodule // RUN: %swiftc_driver -driver-print-actions -emit-executable -emit-module %s 2>&1 | %FileCheck %s -check-prefix=EXEC-AND-MODULE // EXEC-AND-MODULE: 0: input, "{{.*}}actions.swift", swift // EXEC-AND-MODULE: 1: compile, {0}, object // EXEC-AND-MODULE: 2: merge-module, {1}, swiftmodule // EXEC-AND-MODULE: 3: link, {1}, image // RUN: %swiftc_driver -driver-print-actions -g %s 2>&1 | %FileCheck %s -check-prefix=DEBUG // RUN: %swiftc_driver -driver-print-actions -gnone -g %s 2>&1 | %FileCheck %s -check-prefix=DEBUG // DEBUG: 0: input, "{{.*}}actions.swift", swift // DEBUG: 1: compile, {0}, object // DEBUG: 2: merge-module, {1}, swiftmodule // DEBUG: 3: link, {1, 2}, image // RUN: %swiftc_driver -driver-print-actions -gnone %s 2>&1 | %FileCheck %s -check-prefix=BASIC // RUN: %swiftc_driver -driver-print-actions -g -gnone %s 2>&1 | %FileCheck %s -check-prefix=BASIC // RUN: %swiftc_driver -driver-print-actions -g -verify-debug-info %s 2>&1 | %FileCheck %s -check-prefixes=DEBUG // RUN: %swiftc_driver -driver-print-actions -gnone -g -verify-debug-info %s 2>&1 | %FileCheck %s -check-prefixes=DEBUG // RUN: %swiftc_driver -driver-print-actions -gdwarf-types -verify-debug-info %s 2>&1 | %FileCheck %s -check-prefixes=EXEC-AND-MODULE,VERIFY-DEBUG-DWARF // VERIFY-DEBUG-DWARF-TYPES: 0: verify-debug-info, {4}, none // RUN: %swiftc_driver -driver-print-actions -gline-tables-only -verify-debug-info %s 2>&1 | %FileCheck %s -check-prefixes=BASIC,VERIFY-DEBUG-LINE-TABLES // VERIFY-DEBUG-LINE-TABLES-ONLY: 0: verify-debug-info, {3}, none // RUN: %swiftc_driver -driver-print-actions -gnone -verify-debug-info %s 2>&1 | %FileCheck %s -check-prefixes=MISSING-DEBUG-OPTION // RUN: %swiftc_driver -driver-print-actions -g -gnone -verify-debug-info %s 2>&1 | %FileCheck %s -check-prefixes=MISSING-DEBUG-OPTION // MISSING-DEBUG-OPTION: warning: ignoring '-verify-debug-info'; no debug info is being generated // MISSING-DEBUG-OPTION: 0: input, "{{.*}}actions.swift", swift // MISSING-DEBUG-OPTION: 1: compile, {0}, object // MISSING-DEBUG-OPTION: 2: link, {1}, image // RUN: %swiftc_driver -driver-print-actions -g -c %s 2>&1 | %FileCheck %s -check-prefix=DEBUG-OBJECT // DEBUG-OBJECT: 0: input, "{{.*}}actions.swift", swift // DEBUG-OBJECT: 1: compile, {0}, object // DEBUG-OBJECT-NOT: merge-module // RUN: %swiftc_driver -driver-print-actions -g -emit-executable -emit-module %s 2>&1 | %FileCheck %s -check-prefix=DEBUG-MODULE // RUN: %swiftc_driver -driver-print-actions -gnone -g -emit-executable -emit-module %s 2>&1 | %FileCheck %s -check-prefix=DEBUG-MODULE // DEBUG-MODULE: 0: input, "{{.*}}actions.swift", swift // DEBUG-MODULE: 1: compile, {0}, object // DEBUG-MODULE: 2: merge-module, {1}, swiftmodule // DEBUG-MODULE: 3: link, {1, 2}, image // RUN: %swiftc_driver -driver-print-actions -gnone -emit-executable -emit-module %s 2>&1 | %FileCheck %s -check-prefix=EXEC-AND-MODULE // RUN: %swiftc_driver -driver-print-actions -g -gnone -emit-executable -emit-module %s 2>&1 | %FileCheck %s -check-prefix=EXEC-AND-MODULE // RUN: %swiftc_driver -driver-print-actions %S/Inputs/main.swift %S/../Inputs/empty.swift %s -module-name actions 2>&1 | %FileCheck %s -check-prefix=MULTI // MULTI: 0: input, "{{.*}}Inputs/main.swift", swift // MULTI: 1: compile, {0}, object // MULTI: 2: input, "{{.*}}Inputs/empty.swift", swift // MULTI: 3: compile, {2}, object // MULTI: 4: input, "{{.*}}actions.swift", swift // MULTI: 5: compile, {4}, object // MULTI: 6: link, {1, 3, 5}, image // RUN: %swiftc_driver -driver-print-actions -g %S/Inputs/main.swift %S/../Inputs/empty.swift %s -module-name actions 2>&1 | %FileCheck %s -check-prefix=DEBUG-MULTI // DEBUG-MULTI: 0: input, "{{.*}}Inputs/main.swift", swift // DEBUG-MULTI: 1: compile, {0}, object // DEBUG-MULTI: 2: input, "{{.*}}Inputs/empty.swift", swift // DEBUG-MULTI: 3: compile, {2}, object // DEBUG-MULTI: 4: input, "{{.*}}actions.swift", swift // DEBUG-MULTI: 5: compile, {4}, object // DEBUG-MULTI: 6: merge-module, {1, 3, 5}, swiftmodule // DEBUG-MULTI: 7: link, {1, 3, 5, 6}, image // RUN: touch %t/a.o %t/b.o // RUN: %swiftc_driver -driver-print-actions %t/a.o %t/b.o -o main 2>&1 | %FileCheck %s -check-prefix=LINK-ONLY // RUN: %swiftc_driver -driver-print-actions -g %t/a.o %t/b.o -o main 2>&1 | %FileCheck %s -check-prefix=LINK-ONLY // LINK-ONLY: 0: input, "{{.*}}/a.o", object // LINK-ONLY: 1: input, "{{.*}}/b.o", object // LINK-ONLY: 2: link, {0, 1}, image // RUN: touch %t/a.swiftmodule %t/b.swiftmodule // RUN: %swiftc_driver -driver-print-actions -g %t/a.o %t/b.o %t/a.swiftmodule %t/b.swiftmodule -o main 2>&1 | %FileCheck %s -check-prefix=DEBUG-LINK-ONLY // DEBUG-LINK-ONLY: 0: input, "{{.*}}/a.o", object // DEBUG-LINK-ONLY: 1: input, "{{.*}}/b.o", object // DEBUG-LINK-ONLY: 2: input, "{{.*}}/a.swiftmodule", swiftmodule // DEBUG-LINK-ONLY: 3: input, "{{.*}}/b.swiftmodule", swiftmodule // DEBUG-LINK-ONLY: 4: link, {0, 1, 2, 3}, image // RUN: touch %t/c.swift // RUN: %swiftc_driver -driver-print-actions %t/c.swift %t/a.o %t/b.o %t/a.swiftmodule %t/b.swiftmodule -o main 2>&1 | %FileCheck %s -check-prefix=LINK-SWIFTMODULES // LINK-SWIFTMODULES: 0: input, "{{.*}}/c.swift", swift // LINK-SWIFTMODULES: 1: compile, {0}, object // LINK-SWIFTMODULES: 2: input, "{{.*}}/a.o", object // LINK-SWIFTMODULES: 3: input, "{{.*}}/b.o", object // LINK-SWIFTMODULES: 4: input, "{{.*}}/a.swiftmodule", swiftmodule // LINK-SWIFTMODULES: 5: input, "{{.*}}/b.swiftmodule", swiftmodule // LINK-SWIFTMODULES: 6: link, {1, 2, 3, 4, 5}, image // RUN: %swiftc_driver -driver-print-actions -g %t/c.swift %t/a.o %t/b.o %t/a.swiftmodule %t/b.swiftmodule -o main 2>&1 | %FileCheck %s -check-prefix=LINK-DEBUG-SWIFTMODULES // LINK-DEBUG-SWIFTMODULES: 0: input, "{{.*}}/c.swift", swift // LINK-DEBUG-SWIFTMODULES: 1: compile, {0}, object // LINK-DEBUG-SWIFTMODULES: 2: input, "{{.*}}/a.o", object // LINK-DEBUG-SWIFTMODULES: 3: input, "{{.*}}/b.o", object // LINK-DEBUG-SWIFTMODULES: 4: input, "{{.*}}/a.swiftmodule", swiftmodule // LINK-DEBUG-SWIFTMODULES: 5: input, "{{.*}}/b.swiftmodule", swiftmodule // LINK-DEBUG-SWIFTMODULES: 6: merge-module, {1}, swiftmodule // LINK-DEBUG-SWIFTMODULES: 7: link, {1, 2, 3, 4, 5, 6}, image // RUN: touch %t/a.o %t/b.o // RUN: %swiftc_driver -driver-print-actions %t/a.o %s -o main 2>&1 | %FileCheck %s -check-prefix=COMPILE-PLUS-OBJECT // COMPILE-PLUS-OBJECT: 0: input, "{{.*}}/a.o", object // COMPILE-PLUS-OBJECT: 1: input, "{{.*}}actions.swift", swift // COMPILE-PLUS-OBJECT: 2: compile, {1}, object // COMPILE-PLUS-OBJECT: 3: link, {0, 2}, image // RUN: %swiftc_driver -driver-print-actions %S/Inputs/main.swift %S/../Inputs/empty.swift %s -module-name actions -force-single-frontend-invocation 2>&1 | %FileCheck %s -check-prefix=WHOLE-MODULE // WHOLE-MODULE: 0: input, "{{.*}}Inputs/main.swift", swift // WHOLE-MODULE: 1: input, "{{.*}}Inputs/empty.swift", swift // WHOLE-MODULE: 2: input, "{{.*}}actions.swift", swift // WHOLE-MODULE: 3: compile, {0, 1, 2}, object // WHOLE-MODULE: 4: link, {3}, image
apache-2.0
929aaa4e41afe78e13a20fd2971065f2
56.030675
196
0.662973
2.990991
false
false
true
false
blockchain/My-Wallet-V3-iOS
Modules/WalletPayload/Sources/WalletPayloadKitMock/WalletUpgradeSpy.swift
1
780
// Copyright © Blockchain Luxembourg S.A. All rights reserved. @testable import WalletPayloadKit import Combine import ToolKit import WalletPayloadDataKit final class WalletUpgraderSpy: WalletUpgraderAPI { let realUpgrader: WalletUpgraderAPI init(realUpgrader: WalletUpgraderAPI) { self.realUpgrader = realUpgrader } var upgradedNeededCalled: Bool = false func upgradedNeeded(wrapper: Wrapper) -> Bool { upgradedNeededCalled = true return realUpgrader.upgradedNeeded(wrapper: wrapper) } var performUpgradeCalled: Bool = false func performUpgrade(wrapper: Wrapper) -> AnyPublisher<Wrapper, WalletUpgradeError> { performUpgradeCalled = true return realUpgrader.performUpgrade(wrapper: wrapper) } }
lgpl-3.0
2d0dfebb9ea0230eb98186d3c815553e
26.821429
88
0.739409
4.210811
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/WalletPayload/Sources/WalletPayloadKit/Services/Sync/WalletSync.swift
1
10112
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Errors import Foundation import ObservabilityKit import ToolKit protocol WalletSyncAPI { /// Syncs the given `Wrapper` of a `Wallet` with the backend. /// - Parameters: /// - wrapper: An updated `Wrapper` object to be sent to the server /// - password: A `String` to be used as a password for the encryption /// - Returns: `AnyPublisher<EmptyValue, WalletSyncError>` func sync( wrapper: Wrapper, password: String ) -> AnyPublisher<EmptyValue, WalletSyncError> } /// Responsible for syncing the latest changes of `Wallet` to backend final class WalletSync: WalletSyncAPI { private let walletHolder: WalletHolderAPI private let walletRepo: WalletRepoAPI private let payloadCrypto: PayloadCryptoAPI private let walletEncoder: WalletEncodingAPI private let operationQueue: DispatchQueue private let saveWalletRepository: SaveWalletRepositoryAPI private let syncPubKeysAddressesProvider: SyncPubKeysAddressesProviderAPI private let tracer: LogMessageServiceAPI private let logger: NativeWalletLoggerAPI private let checksumProvider: (Data) -> String init( walletHolder: WalletHolderAPI, walletRepo: WalletRepoAPI, payloadCrypto: PayloadCryptoAPI, walletEncoder: WalletEncodingAPI, saveWalletRepository: SaveWalletRepositoryAPI, syncPubKeysAddressesProvider: SyncPubKeysAddressesProviderAPI, tracer: LogMessageServiceAPI, logger: NativeWalletLoggerAPI, operationQueue: DispatchQueue, checksumProvider: @escaping (Data) -> String ) { self.walletHolder = walletHolder self.walletRepo = walletRepo self.payloadCrypto = payloadCrypto self.walletEncoder = walletEncoder self.saveWalletRepository = saveWalletRepository self.syncPubKeysAddressesProvider = syncPubKeysAddressesProvider self.operationQueue = operationQueue self.checksumProvider = checksumProvider self.tracer = tracer self.logger = logger } /// Syncs the given `Wrapper` of a `Wallet` with the backend. /// - Parameters: /// - wrapper: An updated `Wrapper` object to be sent to the server /// - password: A `String` to be used as a password for the encryption /// - Returns: `AnyPublisher<EmptyValue, WalletSyncError>` func sync( wrapper: Wrapper, password: String ) -> AnyPublisher<EmptyValue, WalletSyncError> { let saveOperations = saveOperations( walletEncoder: walletEncoder, payloadCrypto: payloadCrypto, logger: logger, checksumProvider: checksumProvider, saveWalletRepository: saveWalletRepository, syncPubKeysAddressesProvider: syncPubKeysAddressesProvider ) return Just(wrapper) .receive(on: operationQueue) .logMessageOnOutput(logger: logger, message: { wrapper in "Wrapper to be synced: \(wrapper)" }) .flatMap { wrapper -> AnyPublisher<WalletCreationPayload, WalletSyncError> in saveOperations(wrapper, password) .eraseToAnyPublisher() } .logErrorOrCrash(tracer: tracer) .flatMap { [walletRepo] payload -> AnyPublisher<WalletCreationPayload, Never> in walletRepo.set(keyPath: \.credentials.password, value: password) .get() .map { _ in payload } .eraseToAnyPublisher() } .flatMap { [walletRepo] payload -> AnyPublisher<WalletCreationPayload, Never> in updateCachedWalletPayload( encodedPayload: payload, walletRepo: walletRepo, wrapper: wrapper ) .map { _ in payload } .eraseToAnyPublisher() } .map { [walletHolder] payload -> WalletState in // update the wrapper with the new checksum let wrapper = updateWrapper(checksum: payload.checksum, using: wrapper) // check the current state of the walletState and update appropriately guard let state = walletHolder.provideWalletState() else { return .partially(loaded: .justWrapper(wrapper)) } guard let metadata = state.metadata else { return .partially(loaded: .justWrapper(wrapper)) } return .loaded(wrapper: wrapper, metadata: metadata) } .flatMap { [walletHolder] walletState -> AnyPublisher<Void, WalletSyncError> in walletHolder.hold(walletState: walletState) .mapToVoid() .mapError(to: WalletSyncError.self) .eraseToAnyPublisher() } .map { _ in EmptyValue.noValue } .eraseToAnyPublisher() } } /// Performs operations needed for saving the `Wallet` to the backend /// 1) Encrypts and verify payload /// 2) Encodes the encrypted payload /// 3) Syncs the wallet with the backend /// - Parameters: /// - walletEncoder: A `WalletEncoderAPI` for encoding the payload /// - payloadCrypto: A `PayloadCryptoAPI` for encrypting/decrypting the payload /// - checksumProvider: A `(Data) -> String` closure that applies a checksum /// - saveWalletRepository: A `SaveWalletRepositoryAPI` for saving the wallet to the backend /// - Returns: A closure `(Wrapper, Password) -> AnyPublisher<WalletCreationPayload, WalletSyncError>` // swiftlint:disable function_parameter_count private func saveOperations( walletEncoder: WalletEncodingAPI, payloadCrypto: PayloadCryptoAPI, logger: NativeWalletLoggerAPI, checksumProvider: @escaping (Data) -> String, saveWalletRepository: SaveWalletRepositoryAPI, syncPubKeysAddressesProvider: SyncPubKeysAddressesProviderAPI ) -> (_ wrapper: Wrapper, _ password: String) -> AnyPublisher<WalletCreationPayload, WalletSyncError> { { wrapper, password -> AnyPublisher<WalletCreationPayload, WalletSyncError> in // encrypt and then decrypt the wrapper for verification encryptAndVerifyWrapper( walletEncoder: walletEncoder, encryptor: payloadCrypto, logger: logger, password: password, wrapper: wrapper ) .mapError(WalletSyncError.verificationFailure) .flatMap { [walletEncoder, checksumProvider] payload -> AnyPublisher<WalletCreationPayload, WalletSyncError> in walletEncoder.encode(payload: payload, applyChecksum: checksumProvider) .mapError(WalletSyncError.encodingError) .eraseToAnyPublisher() } .flatMap { [syncPubKeysAddressesProvider, logger] payload -> AnyPublisher<(WalletCreationPayload, String?), WalletSyncError> in guard wrapper.syncPubKeys else { logger.log(message: "syncPubKeys not required", metadata: nil) return .just((payload, nil)) } // To get notifications working we need to pass a list of lookahead addresses logger.log(message: "syncPubKeys required", metadata: nil) let accounts = wrapper.wallet.defaultHDWallet?.accounts ?? [] return syncPubKeysAddressesProvider.provideAddresses( active: wrapper.wallet.spendableActiveAddresses, accounts: accounts ) .mapError(WalletSyncError.syncPubKeysFailure) .map { addresses in (payload, addresses) } .logMessageOnOutput(logger: logger, message: { _, addresses in let addresses = addresses ?? "" return "[Sync] Addresses to sync:\n \(addresses)" }) .eraseToAnyPublisher() } .logMessageOnOutput(logger: logger, message: { payload, _ in "[Sync] !!! About to sync \(payload)" }) .flatMap { [saveWalletRepository] payload, addresses -> AnyPublisher<WalletCreationPayload, WalletSyncError> in saveWalletRepository.saveWallet( payload: payload, addresses: addresses ) .mapError(WalletSyncError.networkFailure) .map { _ in payload } .eraseToAnyPublisher() } .logMessageOnOutput(logger: logger, message: { _ in "Wallet synced successfully" }) .eraseToAnyPublisher() } } /// Creates a new `Wrapper` with an updated checksum /// - Parameters: /// - checksum: A `String` value /// - wrapper: A `Wrapper` to be recreated /// - Returns: `Wrapper` private func updateWrapper( checksum: String, using wrapper: Wrapper ) -> Wrapper { Wrapper( pbkdf2Iterations: Int(wrapper.pbkdf2Iterations), version: wrapper.version, payloadChecksum: checksum, language: wrapper.language, syncPubKeys: wrapper.syncPubKeys, wallet: wrapper.wallet ) } /// Updates the cached version of `WalletPayload` on `WalletRepo` /// - Returns: `AnyPublisher<Void, Never>` private func updateCachedWalletPayload( encodedPayload: WalletCreationPayload, walletRepo: WalletRepoAPI, wrapper: Wrapper ) -> AnyPublisher<Void, Never> { let currentWalletPayload: WalletPayload = walletRepo.walletPayload let updatedPayload = WalletPayload( guid: encodedPayload.guid, authType: currentWalletPayload.authType, language: encodedPayload.language, shouldSyncPubKeys: wrapper.syncPubKeys, time: Date(), payloadChecksum: encodedPayload.checksum, payload: try? JSONDecoder().decode(WalletPayloadWrapper.self, from: encodedPayload.innerPayload) ) return walletRepo.set(keyPath: \.walletPayload, value: updatedPayload) .get() .mapToVoid() .eraseToAnyPublisher() }
lgpl-3.0
0a045fe145e604b092d242199a74a217
40.954357
119
0.644546
5.065631
false
false
false
false
xivol/Swift-CS333
assignments/task5/schedule/schedule/Connection+Request.swift
2
1445
// // Connection+Request.swift // schedule // // Created by Илья Лошкарёв on 31.03.17. // Copyright © 2017 mmcs. All rights reserved. // import Foundation import UIKit extension Connection { static var defaultRetryInterval: TimeInterval { return 5 } static func request(_ block: @escaping () -> ()) { retry(every: defaultRetryInterval, withRequest: block) } static func retry(every retryInterval: TimeInterval, withRequest request: @escaping () -> ()) { UIApplication.shared.isNetworkActivityIndicatorVisible = true let timer = Timer.scheduledTimer(withTimeInterval: retryInterval, repeats: true) { timer in if Connection.isAvaliable { request() timer.invalidate() UIApplication.shared.isNetworkActivityIndicatorVisible = false } else { DispatchQueue.main.async { let alert = UIAlertController(title: nil, message: "Network connection is required", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) if let vc = UIApplication.shared.delegate?.window??.rootViewController { vc.present(alert, animated: true) } } } } timer.fire() } }
mit
6e128a4f36fc3808c6ca248c27e1e747
32.302326
128
0.577514
5.343284
false
false
false
false
coodly/CoreDataPersistence
Sources/CoreDataPersistence/NSManagedObjectContext+Extensions.swift
2
6695
/* * Copyright 2015 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 CoreData public extension NSPredicate { static let truePredicate = NSPredicate(format: "TRUEPREDICATE") } extension NSManagedObjectContext { public func insertEntity<T: NSManagedObject>() -> T { return NSEntityDescription.insertNewObject(forEntityName: T.entityName(), into: self) as! T } public func fetch<T: NSManagedObject>(predicate: NSPredicate = .truePredicate, sort: [NSSortDescriptor]? = nil, limit: Int? = nil) -> [T] { let request: NSFetchRequest<T> = NSFetchRequest(entityName: T.entityName()) request.predicate = predicate if let limit = limit { request.fetchLimit = limit } request.sortDescriptors = sort do { return try fetch(request) } catch { Logging.log("Fetch \(T.entityName()) failure. Error \(error)") return [] } } public func fetchFirst<T: NSManagedObject>(predicate: NSPredicate = .truePredicate, sort: [NSSortDescriptor] = []) -> T? { let request: NSFetchRequest<T> = NSFetchRequest(entityName: T.entityName()) request.predicate = predicate request.fetchLimit = 1 request.sortDescriptors = sort do { let result = try fetch(request) return result.first } catch { Logging.log("Fetch \(T.entityName()) failure. Error \(error)") return nil } } public func fetchEntity<T: NSManagedObject, V: Any>(where name: String, hasValue: V) -> T? { let attributePredicate = predicate(for: name, withValue: hasValue) return fetchFirst(predicate: attributePredicate) } public func predicate<V: Any>(for attribute: String, withValue: V) -> NSPredicate { let predicate: NSPredicate switch(withValue) { case is String: predicate = NSPredicate(format: "%K ==[c] %@", argumentArray: [attribute, withValue]) default: predicate = NSPredicate(format: "%K = %@", argumentArray: [attribute, withValue]) } return predicate } public func sumOfDecimalProperty<T: NSManagedObject>(onType type: T.Type, name: String, predicate: NSPredicate = .truePredicate) -> NSDecimalNumber { let request: NSFetchRequest<NSDictionary> = NSFetchRequest(entityName: T.entityName()) request.resultType = .dictionaryResultType request.predicate = predicate let sumKey = "sumOfProperty" let expression = NSExpressionDescription() expression.name = sumKey expression.expression = NSExpression(forKeyPath: "@sum.\(name)") expression.expressionResultType = .decimalAttributeType request.propertiesToFetch = [expression] do { let result = try fetch(request) if let first = result.first, let value = first[sumKey] as? NSDecimalNumber { return value } Logging.log("Will return zero for sum of \(name)") return NSDecimalNumber.zero } catch { Logging.log("addDecimalProperty error: \(error)") return NSDecimalNumber.notANumber } } public func count<T: NSManagedObject>(instancesOf entity: T.Type, predicate: NSPredicate = .truePredicate) -> Int { let request: NSFetchRequest<NSNumber> = NSFetchRequest(entityName: T.entityName()) request.predicate = predicate do { return try count(for: request) } catch let error as NSError { fatalError("Count failed: \(error)") } } @available(iOS 9, tvOS 9, macOS 10.12, *) public func fetchedController<T: NSFetchRequestResult>(predicate: NSPredicate? = nil, sort: [NSSortDescriptor], batchSize: Int = 0, sectionNameKeyPath: String? = nil) -> NSFetchedResultsController<T> { let fetchRequest: NSFetchRequest<T> = NSFetchRequest(entityName: T.entityName()) fetchRequest.predicate = predicate fetchRequest.sortDescriptors = sort fetchRequest.fetchBatchSize = batchSize let fetchedController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self, sectionNameKeyPath: sectionNameKeyPath, cacheName: nil) do { try fetchedController.performFetch() } catch { Logging.log("Fetch error: \(error)") } return fetchedController } public func has<T: NSManagedObject, V: Any>(entity type: T.Type, where attribute: String, is value: V) -> Bool { return count(instancesOf: type, predicate: predicate(for: attribute, withValue: value)) == 1 } public func inCurrentContext<T: NSManagedObject>(entities: [T]) -> [T] { var result = [T]() for e in entities { result.append(inCurrentContext(entity: e)) } return result } public func inCurrentContext<T: NSManagedObject>(entity: T) -> T { return object(with: entity.objectID) as! T } public func delete<T: NSManagedObject>(objects: [T]) { for d in objects { delete(d) } } public func fetchAttribute<T: NSManagedObject, Result>(named: String, on entity: T.Type, limit: Int? = nil, predicate: NSPredicate = .truePredicate, distinctResults: Bool = false) -> [Result] { let request: NSFetchRequest<NSDictionary> = NSFetchRequest(entityName: T.entityName()) request.resultType = .dictionaryResultType request.propertiesToFetch = [named] request.returnsDistinctResults = distinctResults request.predicate = predicate if let limit = limit { request.fetchLimit = limit } do { let objects = try fetch(request) return objects.compactMap({ $0[named] as? Result }) } catch { Logging.log("fetchEntityAttribute error: \(error)") return [] } } }
apache-2.0
599cf8d8c6b0e9a13e5fdfe7a9ed577a
37.039773
205
0.623301
5.011228
false
false
false
false
Kievkao/YoutubeClassicPlayer
ClassicalPlayer/Screens/VideosList/Cells/VideoCellViewModel.swift
1
1237
// // VideoCellViewModel.swift // ClassicalPlayer // // Created by Andrii Kravchenko on 08.02.18. // Copyright © 2018 Kievkao. All rights reserved. // import UIKit import RxSwift protocol VideoCellViewModelProtocol { var name: String? { get } var image: Observable<UIImage?> { get } func loadImage() func cancelImageLoading() } class VideoCellViewModel: VideoCellViewModelProtocol { private let video: Video private let imagesLoader: ImagesLoaderServiceProtocol var name: String? { return video.title } var image: Observable<UIImage?> { return imageVariable.asObservable() } private let imageVariable = Variable<UIImage?>(nil) init(imagesLoader: ImagesLoaderServiceProtocol, video: Video) { self.imagesLoader = imagesLoader self.video = video } func loadImage() { guard let imageURL = video.thumbnailURL else { return } imagesLoader.loadImageFor(imageURL: imageURL) { [weak self] image in self?.imageVariable.value = image } } func cancelImageLoading() { if let imageURL = video.thumbnailURL { imagesLoader.cancelImageLoadingFor(imageURL: imageURL) } } }
mit
130fda32c3445529a57043d482aa9a11
25.869565
76
0.665858
4.510949
false
false
false
false
wikimedia/apps-ios-wikipedia
Wikipedia/Code/WelcomePageViewController.swift
1
8679
import UIKit protocol PageViewControllerViewLifecycleDelegate: AnyObject { func pageViewControllerDidAppear(_ pageViewController: UIPageViewController) } final class WelcomePageViewController: UIPageViewController { weak var viewLifecycleDelegate: PageViewControllerViewLifecycleDelegate? private let allViewControllers: [UIViewController] private lazy var pageControl: UIPageControl? = { return view.wmf_firstSubviewOfType(UIPageControl.self) }() private let skipButton = UIButton(type: .system) private let nextButton = UIButton(type: .system) private let buttonHeight: CGFloat = 40 private let buttonHorizontalSpacing: CGFloat = 10 private let buttonXOffset: CGFloat = 88 private var theme = Theme.standard required init(viewControllers: [UIViewController]) { allViewControllers = viewControllers super.init(transitionStyle: .scroll, navigationOrientation: .horizontal) dataSource = self delegate = self } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() assert(allViewControllers.count >= 2, "Expected allViewControllers to contain at least 2 elements") if let firstViewController = allViewControllers.first { setViewControllers([firstViewController], direction: direction, animated: true) if let viewLifecycleDelegate = firstViewController as? PageViewControllerViewLifecycleDelegate { self.viewLifecycleDelegate = viewLifecycleDelegate } } addPageControlButtons() apply(theme: theme) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) viewLifecycleDelegate?.pageViewControllerDidAppear(self) } private func addPageControlButtons() { addSkipButton() addNextButton() } private func addNextButton() { nextButton.translatesAutoresizingMaskIntoConstraints = false nextButton.setTitle(CommonStrings.nextTitle, for: .normal) nextButton.titleLabel?.numberOfLines = 1 nextButton.addTarget(self, action: #selector(next(_:)), for: .touchUpInside) view.addSubview(nextButton) let heightConstraint = nextButton.heightAnchor.constraint(equalToConstant: buttonHeight) let bottomConstraint = nextButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) let leadingConstraint = nextButton.leadingAnchor.constraint(lessThanOrEqualTo: view.centerXAnchor, constant: buttonXOffset) let trailingConstraint = nextButton.trailingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: buttonHorizontalSpacing) NSLayoutConstraint.activate([ heightConstraint, bottomConstraint, leadingConstraint, trailingConstraint ]) } private func addSkipButton() { skipButton.translatesAutoresizingMaskIntoConstraints = false skipButton.setTitle(CommonStrings.skipTitle, for: .normal) skipButton.titleLabel?.numberOfLines = 1 skipButton.addTarget(self, action: #selector(skip(_:)), for: .touchUpInside) view.addSubview(skipButton) let heightConstraint = skipButton.heightAnchor.constraint(equalToConstant: buttonHeight) let bottomConstraint = skipButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor) let leadingConstraint = skipButton.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: buttonHorizontalSpacing) let trailingConstraint = skipButton.trailingAnchor.constraint(lessThanOrEqualTo: view.centerXAnchor, constant: -buttonXOffset) NSLayoutConstraint.activate([ heightConstraint, bottomConstraint, leadingConstraint, trailingConstraint ]) } @objc private func next(_ sender: UIButton) { guard let visibleViewController = visibleViewController, let nextViewController = viewController(after: visibleViewController) else { return } view.isUserInteractionEnabled = false animatePageControlButtons(for: nextViewController) setViewControllers([nextViewController], direction: direction, animated: true) { _ in self.view.isUserInteractionEnabled = true } } @objc private func skip(_ sender: UIButton) { dismiss(animated: true) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) let buttonFont = UIFont.wmf_font(.semiboldFootnote, compatibleWithTraitCollection: traitCollection) nextButton.titleLabel?.font = buttonFont skipButton.titleLabel?.font = buttonFont } private var direction: UIPageViewController.NavigationDirection { return UIApplication.shared.wmf_isRTL ? .reverse : .forward } private func viewController(at index: Int) -> UIViewController? { guard index >= 0, allViewControllers.count > index else { return nil } return allViewControllers[index] } private var visibleViewController: UIViewController? { return viewControllers?.first } } extension WelcomePageViewController: Themeable { func apply(theme: Theme) { guard viewIfLoaded != nil else { self.theme = theme return } allViewControllers.forEach { ($0 as? Themeable)?.apply(theme: theme) } view.backgroundColor = theme.colors.midBackground pageControl?.pageIndicatorTintColor = theme.colors.pageIndicator pageControl?.currentPageIndicatorTintColor = theme.colors.pageIndicatorCurrent nextButton.tintColor = theme.colors.link skipButton.tintColor = UIColor(0xA2A9B1) nextButton.setTitleColor(theme.colors.disabledText, for: .disabled) } } extension WelcomePageViewController: UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { guard let index = allViewControllers.firstIndex(of: viewController) else { return nil } let beforeIndex = index - 1 return self.viewController(at: beforeIndex) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { return self.viewController(after: viewController) } private func viewController(after viewController: UIViewController) -> UIViewController? { guard let index = allViewControllers.firstIndex(of: viewController) else { return nil } let afterIndex = index + 1 return self.viewController(at: afterIndex) } } extension WelcomePageViewController: UIPageViewControllerDelegate { func presentationCount(for pageViewController: UIPageViewController) -> Int { return allViewControllers.count } func presentationIndex(for pageViewController: UIPageViewController) -> Int { guard let visibleViewController = pageViewController.viewControllers?.first, let presentationIndex = allViewControllers.firstIndex(of: visibleViewController) else { return 0 } return presentationIndex } func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { guard completed else { return } let index = presentationIndex(for: pageViewController) guard let viewController = self.viewController(at: index) else { return } animatePageControlButtons(for: viewController) } private func animatePageControlButtons(for viewController: UIViewController) { let index = allViewControllers.firstIndex(of: viewController) let isLast = allViewControllers.count - 1 == index let alpha: CGFloat = isLast ? 0 : 1 nextButton.isEnabled = !isLast guard pageControl?.alpha != alpha else { return } UIViewPropertyAnimator(duration: 0.3, curve: .linear) { self.skipButton.alpha = alpha self.nextButton.alpha = alpha self.pageControl?.alpha = alpha }.startAnimation() } }
mit
86e45ddc09bbb7ac29e5b4c4ffe3b228
39.746479
190
0.702155
5.977273
false
false
false
false
duliodenis/battlebots
battlebots/battlebots/ViewController.swift
1
2214
// // ViewController.swift // battlebots // // Created by Dulio Denis on 11/3/15. // Copyright © 2015 Dulio Denis. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var printLabel: UILabel! @IBOutlet weak var playerHealthPointLabel: UILabel! @IBOutlet weak var enemyHealthPointLabel: UILabel! @IBOutlet weak var enemyImage: UIImageView! @IBOutlet weak var chestButton: UIButton! var player: Player! var enemy: Enemy! var chestMessage: String? override func viewDidLoad() { super.viewDidLoad() player = Player(name: "DirtyLaundry21", healthPoint: 110, attackPower: 20) playerHealthPointLabel.text = "\(player.healthPoint) HP" generateRandomEnemy() } // MARK: Helper Methods func generateRandomEnemy() { let rand = Int(arc4random_uniform(2)) if rand == 0 { enemy = Kimara(startingHealthPoint: 110, startingAttackPower: 12) } else { enemy = DevilWizard(startingHealthPoint: 60, startingAttackPower: 15) } enemyImage.hidden = false } @IBAction func onChestTapped(sender: AnyObject) { chestButton.hidden = true printLabel.text = chestMessage NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "generateRandomEnemy", userInfo: nil, repeats: false) } @IBAction func attackTapped(sender: UIButton!) { if enemy.attemptAttack(player.attackPower) { printLabel.text = "Attacked \(enemy.type) for \(player.attackPower) HP" enemyHealthPointLabel.text = "\(enemy.healthPoint) HP" } else { printLabel.text = "Attack was unsuccessful!" } if let loot = enemy.dropLoot() { player.addItemToInventory(loot) chestMessage = "\(player.name) found \(loot)" chestButton.hidden = false } if !enemy.isAlive { enemyHealthPointLabel.text = "" printLabel.text = "Killed \(enemy.type)" enemyImage.hidden = true } } }
mit
d28ef2c14deab34e27a3ccecdd4278c1
27.74026
129
0.604609
4.470707
false
false
false
false
afarber/ios-newbie
TransApp/TransApp/GameModel.swift
1
900
// // GameModel.swift // TransApp // // Created by Alexander Farber on 05.12.21. // import Foundation import SwiftUI import CoreData struct GameResponse: Codable { let game: GameModel } struct GameModel: Codable, Identifiable { var id: Int32 { gid } let gid: Int32 let letters: [[String?]] let values: [[Int32?]] let tiles: [TileModel]? // the prevous move as an array // create a new Core Data entity and copy the properties func toEntity(viewContext: NSManagedObjectContext) -> GameEntity { let gameEntity = GameEntity(context: viewContext) gameEntity.gid = self.gid gameEntity.lettersArray = self.letters gameEntity.valuesArray = self.values gameEntity.tilesArray = self.tiles return gameEntity } } struct TileModel: Codable { let col: Int let row: Int let value: Int let letter: String }
unlicense
2cfec18793a2a2c412cca30a8fde3246
22.076923
70
0.667778
4.109589
false
false
false
false
kashesoft/kjob-apple
Sources/Worker.swift
1
1862
/* * Copyright (C) 2016 Andrey Kashaed * * 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 class Worker { static func workerQueueingWithMainPriority() -> Worker { return Worker(priority: nil, tag: nil) } static func workerQueueingWithPriority(_ priority: DispatchQoS.QoSClass) -> Worker { return Worker(priority: priority, tag: nil) } static func workerQueueingWithTag(_ tag: String) -> Worker { return Worker(priority: nil, tag: tag) } private let priority: DispatchQoS.QoSClass! private let tag: String! private init(priority: DispatchQoS.QoSClass!, tag: String!) { self.priority = priority self.tag = tag } func workUpTask(_ task: DispatchWorkItem, delay: Double!) { let queue: DispatchQueue if tag != nil { queue = Shell.sharedInstance.getQueue(tag: tag) } else if priority != nil { queue = Shell.newQueue(priority: priority) } else { queue = DispatchQueue.main } if delay != nil { let delayTime = DispatchTime.now() + Double(Int64(delay! * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) queue.asyncAfter(deadline: delayTime, execute: task) } else { queue.async(execute: task) } } }
apache-2.0
36f06ee8e189bef2a14a6231d13e5cc5
31.103448
116
0.643394
4.340326
false
false
false
false
yuwang17/WYExtensionUtil
WYExtensionUtil/WYCGRectExtension.swift
1
2234
// // WYCGRectExtension.swift // Board // // Created by Wang Yu on 12/26/15. // Copyright © 2015 Wang Yu. All rights reserved. // import UIKit extension CGRect { var x: CGFloat { get { return self.origin.x } set { self = CGRectMake(newValue, self.minY, self.width, self.height) } } var y: CGFloat { get { return self.origin.y } set { self = CGRectMake(self.x, newValue, self.width, self.height) } } var width: CGFloat { get { return self.size.width } set { self = CGRectMake(self.x, self.width, newValue, self.height) } } var height: CGFloat { get { return self.size.height } set { self = CGRectMake(self.x, self.minY, self.width, newValue) } } var top: CGFloat { get { return self.origin.y } set { y = newValue } } var bottom: CGFloat { get { return self.origin.y + self.size.height } set { self = CGRectMake(x, newValue - height, width, height) } } var left: CGFloat { get { return self.origin.x } set { self.x = newValue } } var right: CGFloat { get { return x + width } set { self = CGRectMake(newValue - width, y, width, height) } } var midX: CGFloat { get { return self.x + self.width / 2 } set { self = CGRectMake(newValue - width / 2, y, width, height) } } var midY: CGFloat { get { return self.y + self.height / 2 } set { self = CGRectMake(x, newValue - height / 2, width, height) } } var centerPoint: CGPoint { get { return CGPointMake(self.midX, self.midY) } set { self = CGRectMake(newValue.x - width / 2, newValue.y - height / 2, width, height) } } }
mit
0ed43f602cc2c2cdf136e8bc35050f19
18.946429
93
0.442006
4.277778
false
false
false
false
kclowes/HackingWithSwift
Project10/Project10/ViewController.swift
1
3498
// // ViewController.swift // Project10 // // Created by Keri Clowes on 3/29/16. // Copyright © 2016 Keri Clowes. All rights reserved. // import UIKit class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { var people = [Person]() @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(addNewPerson)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return people.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Person", forIndexPath: indexPath) as! PersonCell let person = people[indexPath.item] cell.name.text = person.name let path = getDocumentsDirectory().stringByAppendingPathComponent(person.image) cell.imageView.image = UIImage(contentsOfFile: path) cell.imageView.layer.borderColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3).CGColor cell.imageView.layer.borderWidth = 2 cell.imageView.layer.cornerRadius = 3 cell.layer.cornerRadius = 7 return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let person = people[indexPath.item] let ac = UIAlertController(title: "Rename person", message: nil, preferredStyle: .Alert) ac.addTextFieldWithConfigurationHandler(nil) ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) ac.addAction(UIAlertAction(title: "OK", style: .Default) { [unowned self, ac] _ in let newName = ac.textFields![0] person.name = newName.text! self.collectionView.reloadData() }) presentViewController(ac, animated: true, completion: nil) } func addNewPerson() { let picker = UIImagePickerController() picker.allowsEditing = true picker.delegate = self presentViewController(picker, animated: true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { var newImage: UIImage if let possibleImage = info["UIImagePickerControllerEditedImage"] as? UIImage { newImage = possibleImage } else if let possibleImage = info["UIImagePickerControllerOriginalImage"] as? UIImage { newImage = possibleImage } else { return } let imageName = NSUUID().UUIDString let imagePath = getDocumentsDirectory().stringByAppendingPathComponent(imageName) if let jpegData = UIImageJPEGRepresentation(newImage, 80) { jpegData.writeToFile(imagePath, atomically: true) } dismissViewControllerAnimated(true, completion: nil) let person = Person(name: "Unknown", image: imageName) people.append(person) collectionView.reloadData() } func getDocumentsDirectory() -> NSString { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let documentsDirectory = paths[0] return documentsDirectory } }
mit
b05f9330dc0e61ab24c433af74e09462
31.990566
128
0.742351
5.165436
false
false
false
false
Brightify/Cuckoo
Source/Matching/ParameterMatcherFunctions.swift
2
11410
// // ParameterMatcherFunctions.swift // Cuckoo // // Created by Filip Dolnik on 04.07.16. // Copyright © 2016 Brightify. All rights reserved. // /// Returns an equality matcher. public func equal<T: Equatable>(to value: T) -> ParameterMatcher<T> { return equal(to: value, equalWhen: ==) } /// Returns an identity matcher. @available(*, renamed: "sameInstance(as:)") public func equal<T: AnyObject>(to value: T) -> ParameterMatcher<T> { return equal(to: value, equalWhen: ===) } /// Returns an equality matcher for Array<Equatable> (ordered) public func equal<T: Equatable>(to array: [T]) -> ParameterMatcher<[T]> { return equal(to: array, equalWhen: ==) } /// Returns an equality matcher for Set<Equatable> public func equal<T>(to set: Set<T>) -> ParameterMatcher<Set<T>> { return equal(to: set, equalWhen: ==) } /// Returns an equality matcher for Dictionary<Hashable, Equatable> public func equal<K: Hashable, V: Equatable>(to dictionary: [K: V]) -> ParameterMatcher<[K: V]> { return equal(to: dictionary, equalWhen: ==) } /// Returns a matcher using the supplied function. public func equal<T>(to value: T, equalWhen equalityFunction: @escaping (T, T) -> Bool) -> ParameterMatcher<T> { return ParameterMatcher { return equalityFunction(value, $0) } } /// Returns a matcher matching any Int value. public func anyInt() -> ParameterMatcher<Int> { return ParameterMatcher() } /// Returns a matcher matching any String value. public func anyString() -> ParameterMatcher<String> { return ParameterMatcher() } /// Returns a matcher matching any throwing closure. public func anyThrowingClosure<OUT>() -> ParameterMatcher<() throws -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any throwing closure. public func anyThrowingClosure<IN1, OUT>() -> ParameterMatcher<(IN1) throws -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any throwing closure. public func anyThrowingClosure<IN1, IN2, OUT>() -> ParameterMatcher<(IN1, IN2) throws -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any throwing closure. public func anyThrowingClosure<IN1, IN2, IN3, OUT>() -> ParameterMatcher<(IN1, IN2, IN3) throws -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any throwing closure. public func anyThrowingClosure<IN1, IN2, IN3, IN4, OUT>() -> ParameterMatcher<(IN1, IN2, IN3, IN4) throws -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any throwing closure. public func anyThrowingClosure<IN1, IN2, IN3, IN4, IN5, OUT>() -> ParameterMatcher<(IN1, IN2, IN3, IN4, IN5) throws -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any throwing closure. public func anyThrowingClosure<IN1, IN2, IN3, IN4, IN5, IN6, OUT>() -> ParameterMatcher<(IN1, IN2, IN3, IN4, IN5, IN6) throws -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any throwing closure. public func anyThrowingClosure<IN1, IN2, IN3, IN4, IN5, IN6, IN7, OUT>() -> ParameterMatcher<(IN1, IN2, IN3, IN4, IN5, IN6, IN7) throws -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any non-throwing closure. public func anyClosure<OUT>() -> ParameterMatcher<() -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any non-throwing closure. public func anyClosure<IN1, OUT>() -> ParameterMatcher<(IN1) -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any non-throwing closure. public func anyClosure<IN1, IN2, OUT>() -> ParameterMatcher<(IN1, IN2) -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any non-throwing closure. public func anyClosure<IN1, IN2, IN3, OUT>() -> ParameterMatcher<(IN1, IN2, IN3) -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any non-throwing closure. public func anyClosure<IN1, IN2, IN3, IN4, OUT>() -> ParameterMatcher<(IN1, IN2, IN3, IN4) -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any non-throwing closure. public func anyClosure<IN1, IN2, IN3, IN4, IN5, OUT>() -> ParameterMatcher<(IN1, IN2, IN3, IN4, IN5) -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any non-throwing closure. public func anyClosure<IN1, IN2, IN3, IN4, IN5, IN6, OUT>() -> ParameterMatcher<(IN1, IN2, IN3, IN4, IN5, IN6) -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any non-throwing closure. public func anyClosure<IN1, IN2, IN3, IN4, IN5, IN6, IN7, OUT>() -> ParameterMatcher<(IN1, IN2, IN3, IN4, IN5, IN6, IN7) -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any throwing closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyThrowingClosure<OUT>() -> ParameterMatcher<() async throws -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any throwing closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyThrowingClosure<IN1, OUT>() -> ParameterMatcher<(IN1) async throws -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any throwing closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyThrowingClosure<IN1, IN2, OUT>() -> ParameterMatcher<(IN1, IN2) async throws -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any throwing closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyThrowingClosure<IN1, IN2, IN3, OUT>() -> ParameterMatcher<(IN1, IN2, IN3) async throws -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any throwing closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyThrowingClosure<IN1, IN2, IN3, IN4, OUT>() -> ParameterMatcher<(IN1, IN2, IN3, IN4) async throws -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any throwing closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyThrowingClosure<IN1, IN2, IN3, IN4, IN5, OUT>() -> ParameterMatcher<(IN1, IN2, IN3, IN4, IN5) async throws -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any throwing closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyThrowingClosure<IN1, IN2, IN3, IN4, IN5, IN6, OUT>() -> ParameterMatcher<(IN1, IN2, IN3, IN4, IN5, IN6) async throws -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any throwing closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyThrowingClosure<IN1, IN2, IN3, IN4, IN5, IN6, IN7, OUT>() -> ParameterMatcher<(IN1, IN2, IN3, IN4, IN5, IN6, IN7) async throws -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any non-throwing closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyClosure<OUT>() -> ParameterMatcher<() async -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any non-throwing closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyClosure<IN1, OUT>() -> ParameterMatcher<(IN1) async -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any non-throwing closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyClosure<IN1, IN2, OUT>() -> ParameterMatcher<(IN1, IN2) async -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any non-throwing closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyClosure<IN1, IN2, IN3, OUT>() -> ParameterMatcher<(IN1, IN2, IN3) async -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any non-throwing closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyClosure<IN1, IN2, IN3, IN4, OUT>() -> ParameterMatcher<(IN1, IN2, IN3, IN4) async -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any non-throwing closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyClosure<IN1, IN2, IN3, IN4, IN5, OUT>() -> ParameterMatcher<(IN1, IN2, IN3, IN4, IN5) async -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any non-throwing closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyClosure<IN1, IN2, IN3, IN4, IN5, IN6, OUT>() -> ParameterMatcher<(IN1, IN2, IN3, IN4, IN5, IN6) async -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any non-throwing closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyClosure<IN1, IN2, IN3, IN4, IN5, IN6, IN7, OUT>() -> ParameterMatcher<(IN1, IN2, IN3, IN4, IN5, IN6, IN7) async -> OUT> { return ParameterMatcher() } /// Returns a matcher matching any T value or nil. public func any<T>(_ type: T.Type = T.self) -> ParameterMatcher<T> { return ParameterMatcher() } /// Returns a matcher matching any T value or nil. public func any<T>(_ type: T.Type = T.self) -> ParameterMatcher<T?> { return ParameterMatcher() } /// Returns an equality matcher. public func equal<T: Equatable>(to value: T?) -> ParameterMatcher<T?> { return equal(to: value, equalWhen: ==) } /// Returns an identity matcher. @available(*, renamed: "sameInstance(as:)") public func equal<T: AnyObject>(to value: T?) -> ParameterMatcher<T?> { return equal(to: value, equalWhen: ===) } /// Returns an identity matcher. public func sameInstance<T: AnyObject>(as object: T?) -> ParameterMatcher<T?> { return equal(to: object, equalWhen: ===) } /// Returns an identity matcher. public func sameInstance<T: AnyObject>(as object: T) -> ParameterMatcher<T> { return equal(to: object, equalWhen: ===) } /// Returns a matcher using the supplied function. public func equal<T>(to value: T?, equalWhen equalityFunction: @escaping (T?, T?) -> Bool) -> ParameterMatcher<T?> { return ParameterMatcher { return equalityFunction(value, $0) } } /// Returns a matcher matching any Int value. public func anyInt() -> ParameterMatcher<Int?> { return notNil() } /// Returns a matcher matching any String value. public func anyString() -> ParameterMatcher<String?> { return notNil() } /// Returns a matcher matching any closure. public func anyClosure<IN, OUT>() -> ParameterMatcher<(((IN)) -> OUT)?> { return notNil() } /// Returns a matcher matching any closure. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public func anyClosure<IN, OUT>() -> ParameterMatcher<(((IN)) async -> OUT)?> { return notNil() } public func anyOptionalThrowingClosure<IN, OUT>() -> ParameterMatcher<(((IN)) throws -> OUT)?> { return notNil() } /// Returns a matcher matching any non-nil value. public func notNil<T>() -> ParameterMatcher<T?> { return ParameterMatcher { if case .none = $0 { return false } else { return true } } } /// Returns a matcher matching any nil value. public func isNil<T>() -> ParameterMatcher<T?> { return ParameterMatcher { if case .none = $0 { return true } else { return false } } } /// Returns a matcher negating any matcher it's applied to. public func not<T>(_ matcher: ParameterMatcher<T>) -> ParameterMatcher<T> { return ParameterMatcher { value in !matcher.matches(value) } }
mit
fca41016c8f4814c7fb4a38295cbf6d0
34.877358
151
0.684898
3.509382
false
false
false
false
marcbaldwin/Alto
Alto/Size.swift
1
1838
import Foundation public enum Size { case size } extension Size: DoubleOffset, DoubleAttribute { var nsAttributes: (NSLayoutConstraint.Attribute, NSLayoutConstraint.Attribute) { switch self { case .size: return (.width, .height) } } } extension UIView { @discardableResult public func set(_ attr1: Size, _ relation: Relation, _ view: UIView, _ attr2: Size, priority: Priority? = nil, isActive: Bool = true) -> [NSLayoutConstraint] { return NSLayoutConstraint.create(self, attr1, relation, view, attr2, priority: priority, isActive: isActive) } @discardableResult public func set(_ attr1: Size, _ relation: Relation, _ view: UIView, _ attr2: MultiplierOffset<Size>, priority: Priority? = nil, isActive: Bool = true) -> [NSLayoutConstraint] { return NSLayoutConstraint.create(self, attr1, relation, view, attr2, priority: priority, isActive: isActive) } } public extension Array where Element: UIView { @discardableResult func set(_ attr1: Size, _ relation: Relation, _ view: UIView, _ attr2: Size, priority: Priority? = nil, isActive: Bool = true) -> [NSLayoutConstraint] { return flatMap { $0.set(attr1, relation, view, attr2, priority: priority, isActive: isActive) } } @discardableResult func set(_ attr1: Size, _ relation: Relation, _ view: UIView, _ attr2: MultiplierOffset<Size>, priority: Priority? = nil, isActive: Bool = true) -> [NSLayoutConstraint] { return flatMap { $0.set(attr1, relation, view, attr2, priority: priority, isActive: isActive) } } @discardableResult func set(same attr: Size, priority: Priority? = nil, isActive: Bool = true) -> [NSLayoutConstraint] { return dropLast(1).flatMap { $0.set(attr, .equalTo, last!, attr, priority: priority, isActive: isActive) } } }
mit
fff61d74414f6efec427e5f48e53296b
38.956522
181
0.678455
4.066372
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/Common/Common/Extension/UIButton+EnlargeArea.swift
1
2310
// // EnlargeArea.swift // YaoApp // // Created by 姚隆康 on 2019/5/29. // Copyright © 2019 识货. All rights reserved. // import UIKit private var topNameKey = "topNameKey" private var rightNameKey = "rightNameKey" private var bottomNameKey = "bottomNameKey" private var leftNameKey = "leftNameKey" public extension UIButton { public func setEnlargeArea(areaFloat:CGFloat){ setEnlargeEdge(top: areaFloat, right: areaFloat, bottom: areaFloat, left: areaFloat) } public func setEnlargeEdge(top:CGFloat, right:CGFloat, bottom:CGFloat, left:CGFloat){ objc_setAssociatedObject(self, &topNameKey,NSNumber(floatLiteral: Double(top)) ,.OBJC_ASSOCIATION_COPY_NONATOMIC) objc_setAssociatedObject(self, &rightNameKey,NSNumber(floatLiteral: Double(right)) ,.OBJC_ASSOCIATION_COPY_NONATOMIC) objc_setAssociatedObject(self, &bottomNameKey,NSNumber(floatLiteral: Double(bottom)) ,.OBJC_ASSOCIATION_COPY_NONATOMIC) objc_setAssociatedObject(self, &leftNameKey,NSNumber(floatLiteral: Double(left)) ,.OBJC_ASSOCIATION_COPY_NONATOMIC) } private func enlargedRect() -> CGRect { let topEdge:NSNumber? = objc_getAssociatedObject(self, &topNameKey) as? NSNumber let rightEdge:NSNumber? = objc_getAssociatedObject(self, &rightNameKey) as? NSNumber let bottomEdge:NSNumber? = objc_getAssociatedObject(self, &bottomNameKey) as? NSNumber let leftEdge:NSNumber? = objc_getAssociatedObject(self, &leftNameKey) as? NSNumber if topEdge != nil && rightEdge != nil && bottomEdge != nil && leftEdge != nil { return CGRect(x: bounds.origin.x - CGFloat(leftEdge!.floatValue), y: bounds.origin.y - CGFloat(topEdge!.floatValue), width: bounds.size.width + CGFloat(leftEdge!.floatValue) + CGFloat(rightEdge!.floatValue), height: bounds.size.height + CGFloat(topEdge!.floatValue) + CGFloat(bottomEdge!.floatValue)) } return bounds } open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { if bounds.contains(point) { return super.point(inside: point, with: event) } if enlargedRect().contains(point) { return true } return super.point(inside: point, with: event) } }
apache-2.0
4cc9268630232820d121b51051f7b899
43.211538
312
0.691605
4.195255
false
false
false
false
Wolkabout/WolkSense-Hexiwear-
iOS/Hexiwear/UserCredentials.swift
1
3276
// // Hexiwear application is used to pair with Hexiwear BLE devices // and send sensor readings to WolkSense sensor data cloud // // Copyright (C) 2016 WolkAbout Technology s.r.o. // // Hexiwear 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. // // Hexiwear 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/>. // // // UserCredentials.swift // import Foundation class UserCredentials { let preferences = UserDefaults.standard var accessTokenExpires: Date? { get { let token = preferences.object(forKey: "accessTokenExpires") as? Date return token } set (newToken) { preferences.set(newToken, forKey: "accessTokenExpires") preferences.synchronize() } } var accessToken: String? { get { let token = preferences.object(forKey: "accessToken") as? String return token } set (newToken) { preferences.set(newToken, forKey: "accessToken") preferences.synchronize() } } var refreshToken: String? { get { let token = preferences.object(forKey: "refreshToken") as? String return token } set (newToken) { preferences.set(newToken, forKey: "refreshToken") preferences.synchronize() } } var email: String? { get { let email = preferences.object(forKey: "email") as? String return email } set (newToken) { preferences.set(newToken, forKey: "email") preferences.synchronize() } } func isDemoUser() -> Bool { if let userEmail = self.email, userEmail == demoAccount { return true } return false } func clearCredentials() { accessTokenExpires = nil accessToken = nil refreshToken = nil email = nil preferences.synchronize() } internal func storeCredentials(_ credentials: NSDictionary) { if let accessToken = credentials["accessToken"] as? String, let accessTokenExpires = credentials["accessTokenExpires"] as? String, let refreshToken = credentials["refreshToken"] as? String, let email = credentials["email"] as? String { print("store credentials accessToken: \(accessToken), email: \(email)") self.accessToken = accessToken let dateFormat = DateFormatter() dateFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" self.accessTokenExpires = dateFormat.date(from: accessTokenExpires) self.refreshToken = refreshToken self.email = email } } }
gpl-3.0
399136913ea136e222d767949e0687ee
30.805825
83
0.606838
4.831858
false
false
false
false
Killectro/RxGrailed
RxGrailed/Pods/AlgoliaSearch-Client-Swift/Source/AbstractQuery.swift
1
13236
// // Copyright (c) 2015 Algolia // http://www.algolia.com/ // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation // ---------------------------------------------------------------------------- // IMPLEMENTATION NOTES // ---------------------------------------------------------------------------- // # Typed vs untyped parameters // // All parameters are stored as untyped, string values. They can be // accessed via the low-level `get` and `set` methods (or the subscript // operator). // // Besides, the class provides typed properties, acting as wrappers on top // of the untyped storage (i.e. serializing to and parsing from string // values). // // # Bridgeability // // **This Swift client must be bridgeable to Objective-C.** // // Unfortunately, query parameters with primitive types (Int, Bool...) are not // bridgeable, because all parameters are optional, and primitive optionals are // not bridgeable to Objective-C. // // To avoid polluting too much the Swift interface with suboptimal types, the // following policy is used: // // - Any parameter whose type is representable in Objective-C is implemented // directly in Swift and marked as `@objc`. // // - Any paramater whose type is *not* bridgeable to Objective-C is implemented // a first time as a Swift-only type... // // - ... and supplemented by an Objective-C specific artifact. To guarantee // optimal developer experience, this artifact is: // // - Named with a `z_objc_` prefix in Swift. This makes it clear that they // are Objective-C specific. The leading "z" ensures they are last in // autocompletion. // // - Exposed to Objective-C using the normal (unprefixed name). // // - Not documented. This ensures that it does not appear in the reference // documentation. // // This way, each platform sees a properties with the right name and the most // adequate type. The only drawback is the added clutter of the `z_objc_`-prefixed // properties in Swift. // // There is also an edge case for the `aroundRadiusAll` constant, which is not // documented. // // ## The case of enums // // Enums can only be bridged to Objective-C if their raw type is integral. // We could do that, but since parameters are optional and optional value types // cannot be bridged anyway (see above), this would be pointless: the type // safety of the enum would be lost in the wrapping into `NSNumber`. Therefore, // enums have a string raw value, and the Objective-C bridge uses a plain // `NSString`. // // ## The case of structs // // Auxiliary types used for query parameters, like `LatLng` or `GeoRect`, have // value semantics. However, structs are not bridgeable to Objective-C. Therefore // we use plain classes (inheriting from `NSObject`) and we make them immutable. // // Equality comparison is implemented in those classes only for the sake of // testability (we use comparisons extensively in unit tests). // // ## Annotations // // Properties and methods visible in Objective-C are annotated with `@objc`. // From an implementation point of view, this is not necessary, because `Query` // derives from `NSObject` and thus every brdigeable property/method is // automatically bridged. We use these annotations as hints for maintainers // (so please keep them). // // ---------------------------------------------------------------------------- /// A pair of (latitude, longitude). /// Used in geo-search. /// @objc public class LatLng: NSObject { // IMPLEMENTATION NOTE: Cannot be `struct` because of Objective-C bridgeability. /// Latitude. public let lat: Double /// Longitude. public let lng: Double /// Create a geo location. /// /// - parameter lat: Latitude. /// - parameter lng: Longitude. /// public init(lat: Double, lng: Double) { self.lat = lat self.lng = lng } // MARK: Equatable public override func isEqual(_ object: Any?) -> Bool { if let rhs = object as? LatLng { return self.lat == rhs.lat && self.lng == rhs.lng } else { return false } } } /// A rectangle in geo coordinates. /// Used in geo-search. /// @objc public class GeoRect: NSObject { // IMPLEMENTATION NOTE: Cannot be `struct` because of Objective-C bridgeability. /// One of the rectangle's corners (typically the northwesternmost). public let p1: LatLng /// Corner opposite from `p1` (typically the southeasternmost). public let p2: LatLng /// Create a geo rectangle. /// /// - parameter p1: One of the rectangle's corners (typically the northwesternmost). /// - parameter p2: Corner opposite from `p1` (typically the southeasternmost). /// public init(p1: LatLng, p2: LatLng) { self.p1 = p1 self.p2 = p2 } public override func isEqual(_ object: Any?) -> Bool { if let rhs = object as? GeoRect { return self.p1 == rhs.p1 && self.p2 == rhs.p2 } else { return false } } } /// An abstract search query. /// /// + Warning: This class is not meant to be used directly. Please see `Query` or `PlacesQuery` instead. /// @objc open class AbstractQuery : NSObject, NSCopying { // MARK: - Low-level (untyped) parameters /// Parameters, as untyped values. @objc public private(set) var parameters: [String: String] = [:] /// Get a parameter in an untyped fashion. /// /// - parameter name: The parameter's name. /// - returns: The parameter's value, or nil if a parameter with the specified name does not exist. /// @objc public func parameter(withName name: String) -> String? { return parameters[name] } /// Set a parameter in an untyped fashion. /// This low-level accessor is intended to access parameters that this client does not yet support. /// /// - parameter name: The parameter's name. /// - parameter value: The parameter's value, or nill to remove it. /// @objc public func setParameter(withName name: String, to value: String?) { if value == nil { parameters.removeValue(forKey: name) } else { parameters[name] = value! } } /// Convenience shortcut to `parameter(withName:)` and `setParameter(withName:to:)`. @objc public subscript(index: String) -> String? { get { return parameter(withName: index) } set(newValue) { setParameter(withName: index, to: newValue) } } // MARK: - // MARK: - Miscellaneous @objc override open var description: String { get { return "\(String(describing: type(of: self))){\(parameters)}" } } // MARK: - Initialization /// Construct an empty query. @objc public override init() { } /// Construct a query with the specified low-level parameters. @objc public init(parameters: [String: String]) { self.parameters = parameters } /// Clear all parameters. @objc open func clear() { parameters.removeAll() } // MARK: NSCopying /// Support for `NSCopying`. /// /// + Note: Primarily intended for Objective-C use. Swift coders should use `init(copy:)`. /// @objc open func copy(with zone: NSZone?) -> Any { // NOTE: As per the docs, the zone argument is ignored. return AbstractQuery(parameters: self.parameters) } // MARK: Serialization & parsing /// Return the final query string used in URL. @objc open func build() -> String { return AbstractQuery.build(parameters: parameters) } /// Build a query string from a set of parameters. @objc static public func build(parameters: [String: String]) -> String { var components = [String]() // Sort parameters by name to get predictable output. let sortedParameters = parameters.sorted { $0.0 < $1.0 } for (key, value) in sortedParameters { let escapedKey = key.urlEncodedQueryParam() let escapedValue = value.urlEncodedQueryParam() components.append(escapedKey + "=" + escapedValue) } return components.joined(separator: "&") } internal static func parse(_ queryString: String, into query: AbstractQuery) { let components = queryString.components(separatedBy: "&") for component in components { let fields = component.components(separatedBy: "=") if fields.count < 1 || fields.count > 2 { continue } if let name = fields[0].removingPercentEncoding { let value: String? = fields.count >= 2 ? fields[1].removingPercentEncoding : nil if value == nil { query.parameters.removeValue(forKey: name) } else { query.parameters[name] = value! } } } } // MARK: Equatable override open func isEqual(_ object: Any?) -> Bool { guard let rhs = object as? AbstractQuery else { return false } return self.parameters == rhs.parameters } // MARK: - Helper methods to build & parse URL /// Build a plain, comma-separated array of strings. /// internal static func buildStringArray(_ array: [String]?) -> String? { if array != nil { return array!.joined(separator: ",") } return nil } internal static func parseStringArray(_ string: String?) -> [String]? { if string != nil { // First try to parse the JSON notation: do { if let array = try JSONSerialization.jsonObject(with: string!.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions(rawValue: 0)) as? [String] { return array } } catch { } // Fallback on plain string parsing. return string!.components(separatedBy: ",") } return nil } internal static func buildJSONArray(_ array: [Any]?) -> String? { if array != nil { do { let data = try JSONSerialization.data(withJSONObject: array!, options: JSONSerialization.WritingOptions(rawValue: 0)) if let string = String(data: data, encoding: String.Encoding.utf8) { return string } } catch { } } return nil } internal static func parseJSONArray(_ string: String?) -> [Any]? { if string != nil { do { if let array = try JSONSerialization.jsonObject(with: string!.data(using: String.Encoding.utf8)!, options: JSONSerialization.ReadingOptions(rawValue: 0)) as? [Any] { return array } } catch { } } return nil } internal static func buildUInt(_ int: UInt?) -> String? { return int == nil ? nil : String(int!) } internal static func parseUInt(_ string: String?) -> UInt? { if string != nil { if let intValue = UInt(string!) { return intValue } } return nil } internal static func buildBool(_ bool: Bool?) -> String? { return bool == nil ? nil : String(bool!) } internal static func parseBool(_ string: String?) -> Bool? { if string != nil { switch (string!.lowercased()) { case "true": return true case "false": return false default: if let intValue = Int(string!) { return intValue != 0 } } } return nil } internal static func toNumber(_ bool: Bool?) -> NSNumber? { return bool == nil ? nil : NSNumber(value: bool!) } internal static func toNumber(_ int: UInt?) -> NSNumber? { return int == nil ? nil : NSNumber(value: int!) } }
mit
867d1e71f3b6133b9d035eb7aa7511da
33.20155
184
0.60071
4.546891
false
false
false
false
swilliams/Gliphy
ExampleApp/WatcherViewController.swift
2
952
// // AdvancedViewController.swift // Gliphy // // Created by Scott Williams on 4/30/16. // Copyright © 2016 Tallwave. All rights reserved. // import UIKit struct ConfigSetup { static func setup() { var config = StyleConfig() config.label[UIFontTextStyleHeadline] = "Verdana" config.label[UIFontTextStyleCaption1] = "MarkerFelt-Thin" config.button[UIFontTextStyleHeadline] = "Verdana" config.textField[UIFontTextStyleBody] = "Verdana" config.textField[UIFontTextStyleCaption1] = "Helvetica" StyleWatcher.defaultConfig = config } } class WatcherViewController: UIViewController, UITextFieldDelegate { let watcher = StyleWatcher() override func viewDidLoad() { super.viewDidLoad() watcher.watchViews(inView: view) } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
mit
0f87c6fc7c1415aa19a09f0689914eb2
24.702703
68
0.683491
4.639024
false
true
false
false
codestergit/swift
test/SILGen/materializeForSet.swift
2
34145
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s class Base { var stored: Int = 0 // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet4BaseC6storedSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed Base) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $Base): // CHECK: [[T0:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.stored // CHECK: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer // CHECK: [[T2:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.none // CHECK: [[T3:%.*]] = tuple ([[T1]] : $Builtin.RawPointer, [[T2]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T3]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet4BaseC8computedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Base, @thick Base.Type) -> () { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Base, [[SELFTYPE:%.*]] : $@thick Base.Type): // CHECK: [[T0:%.*]] = load_borrow [[SELF]] // CHECK: [[T1:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[T2:%.*]] = load [trivial] [[T1]] : $*Int // CHECK: [[SETTER:%.*]] = function_ref @_T017materializeForSet4BaseC8computedSifs // CHECK: apply [[SETTER]]([[T2]], [[T0]]) // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet4BaseC8computedSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed Base) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $Base): // CHECK: [[ADDR:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet4BaseC8computedSifg // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: store [[T1]] to [trivial] [[ADDR]] : $*Int // CHECK: [[BUFFER:%.*]] = address_to_pointer [[ADDR]] // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet4BaseC8computedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Base, @thick Base.Type) -> () // CHECK: [[T2:%.*]] = thin_function_to_pointer [[T0]] // CHECK: [[T3:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T2]] : $Builtin.RawPointer // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[T3]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } var computed: Int { get { return 0 } set(value) {} } var storedFunction: () -> Int = { 0 } final var finalStoredFunction: () -> Int = { 0 } var computedFunction: () -> Int { get { return {0} } set {} } static var staticFunction: () -> Int { get { return {0} } set {} } } class Derived : Base {} protocol Abstractable { associatedtype Result var storedFunction: () -> Result { get set } var finalStoredFunction: () -> Result { get set } var computedFunction: () -> Result { get set } static var staticFunction: () -> Result { get set } } // Validate that we thunk materializeForSet correctly when there's // an abstraction pattern present. extension Derived : Abstractable {} // CHECK: sil private [transparent] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14storedFunction6ResultQzycfmytfU_TW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Derived, @thick Derived.Type) -> () // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived, %3 : $@thick Derived.Type): // CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[VALUE:%.*]] = load [take] [[RESULT_ADDR]] : $*@callee_owned () -> @out Int // CHECK-NEXT: function_ref // CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxr_SiIxd_TR : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int // CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) // CHECK-NEXT: [[FN:%.*]] = class_method [[SELF]] : $Base, #Base.storedFunction!setter.1 : (Base) -> (@escaping () -> Int) -> () // CHECK-NEXT: apply [[FN]]([[NEWVALUE]], [[SELF]]) // CHECK-NEXT: end_borrow [[T0]] from %2 // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: sil private [transparent] [thunk] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14storedFunction{{[_0-9a-zA-Z]*}}fmTW // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived): // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $@callee_owned () -> Int // CHECK-NEXT: [[FN:%.*]] = class_method [[SELF]] : $Base, #Base.storedFunction!getter.1 // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]([[SELF]]) // CHECK-NEXT: store [[RESULT]] to [init] [[TEMP]] // CHECK-NEXT: [[RESULT:%.*]] = load [copy] [[TEMP]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxd_SiIxr_TR : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Int // CHECK-NEXT: [[T1:%.*]] = partial_apply [[REABSTRACTOR]]([[RESULT]]) // CHECK-NEXT: destroy_addr [[TEMP]] // CHECK-NEXT: store [[T1]] to [init] [[RESULT_ADDR]] // CHECK-NEXT: [[RESULT_PTR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned () -> @out Int to $Builtin.RawPointer // CHECK-NEXT: function_ref // CHECK-NEXT: [[T2:%.*]] = function_ref @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14storedFunction6ResultQzycfmytfU_TW // CHECK-NEXT: [[T3:%.*]] = thin_function_to_pointer [[T2]] // CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T3]] // CHECK-NEXT: [[T4:%.*]] = tuple ([[RESULT_PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: dealloc_stack [[TEMP]] // CHECK-NEXT: end_borrow [[T0]] from %2 // CHECK-NEXT: return [[T4]] // CHECK: sil private [transparent] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP19finalStoredFunction6ResultQzycfmytfU_TW : // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived, %3 : $@thick Derived.Type): // CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[VALUE:%.*]] = load [take] [[RESULT_ADDR]] : $*@callee_owned () -> @out Int // CHECK-NEXT: // function_ref // CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxr_SiIxd_TR : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int // CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) // CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.finalStoredFunction // CHECK-NEXT: assign [[NEWVALUE]] to [[ADDR]] // CHECK-NEXT: end_borrow [[T0]] from %2 // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: sil private [transparent] [thunk] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP19finalStoredFunction{{[_0-9a-zA-Z]*}}fmTW // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived): // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base // CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.finalStoredFunction // CHECK-NEXT: [[RESULT:%.*]] = load [copy] [[ADDR]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxd_SiIxr_TR : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Int // CHECK-NEXT: [[T1:%.*]] = partial_apply [[REABSTRACTOR]]([[RESULT]]) // CHECK-NEXT: store [[T1]] to [init] [[RESULT_ADDR]] // CHECK-NEXT: [[RESULT_PTR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned () -> @out Int to $Builtin.RawPointer // CHECK-NEXT: function_ref // CHECK-NEXT: [[T2:%.*]] = function_ref @_T017materializeForSet7DerivedCAA12AbstractableA2aDP19finalStoredFunction6ResultQzycfmytfU_TW // CHECK-NEXT: [[T3:%.*]] = thin_function_to_pointer [[T2]] // CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T3]] // CHECK-NEXT: [[T4:%.*]] = tuple ([[RESULT_PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: end_borrow [[T0]] from %2 // CHECK-NEXT: return [[T4]] // CHECK-LABEL: sil private [transparent] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14staticFunction6ResultQzycfmZytfU_TW // CHECK: bb0([[ARG1:%.*]] : $Builtin.RawPointer, [[ARG2:%.*]] : $*Builtin.UnsafeValueBuffer, [[ARG3:%.*]] : $*@thick Derived.Type, [[ARG4:%.*]] : $@thick Derived.Type.Type): // CHECK-NEXT: [[SELF:%.*]] = load [trivial] [[ARG3]] : $*@thick Derived.Type // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[SELF]] : $@thick Derived.Type to $@thick Base.Type // CHECK-NEXT: [[BUFFER:%.*]] = pointer_to_address [[ARG1]] : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[VALUE:%.*]] = load [take] [[BUFFER]] : $*@callee_owned () -> @out Int // CHECK: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxr_SiIxd_TR : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int // CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int // CHECK: [[SETTER_FN:%.*]] = function_ref @_T017materializeForSet4BaseC14staticFunctionSiycfsZ : $@convention(method) (@owned @callee_owned () -> Int, @thick Base.Type) -> () // CHECK-NEXT: apply [[SETTER_FN]]([[NEWVALUE]], [[BASE_SELF]]) : $@convention(method) (@owned @callee_owned () -> Int, @thick Base.Type) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-LABEL: sil private [transparent] [thunk] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14staticFunction6ResultQzycfmZTW // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $@thick Derived.Type): // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[SELF:%.*]] = upcast %2 : $@thick Derived.Type to $@thick Base.Type // CHECK-NEXT: [[OUT:%.*]] = alloc_stack $@callee_owned () -> Int // CHECK: [[GETTER:%.*]] = function_ref @_T017materializeForSet4BaseC14staticFunctionSiycfgZ : $@convention(method) (@thick Base.Type) -> @owned @callee_owned () -> Int // CHECK-NEXT: [[VALUE:%.*]] = apply [[GETTER]]([[SELF]]) : $@convention(method) (@thick Base.Type) -> @owned @callee_owned () -> Int // CHECK-NEXT: store [[VALUE]] to [init] [[OUT]] : $*@callee_owned () -> Int // CHECK-NEXT: [[VALUE:%.*]] = load [copy] [[OUT]] : $*@callee_owned () -> Int // CHECK: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxd_SiIxr_TR : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Int // CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) // CHECK-NEXT: destroy_addr [[OUT]] : $*@callee_owned () -> Int // CHECK-NEXT: store [[NEWVALUE]] to [init] [[RESULT_ADDR]] : $*@callee_owned () -> @out Int // CHECK-NEXT: [[ADDR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned () -> @out Int to $Builtin.RawPointer // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14staticFunction6ResultQzycfmZytfU_TW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout @thick Derived.Type, @thick Derived.Type.Type) -> () // CHECK-NEXT: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout @thick Derived.Type, @thick Derived.Type.Type) -> () to $Builtin.RawPointer // CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] : $Builtin.RawPointer // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[ADDR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: dealloc_stack [[OUT]] : $*@callee_owned () -> Int // CHECK-NEXT: return [[RESULT]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) protocol ClassAbstractable : class { associatedtype Result var storedFunction: () -> Result { get set } var finalStoredFunction: () -> Result { get set } var computedFunction: () -> Result { get set } static var staticFunction: () -> Result { get set } } extension Derived : ClassAbstractable {} protocol Signatures { associatedtype Result var computedFunction: () -> Result { get set } } protocol Implementations {} extension Implementations { var computedFunction: () -> Int { get { return {0} } set {} } } class ImplementingClass : Implementations, Signatures {} struct ImplementingStruct : Implementations, Signatures { var ref: ImplementingClass? } class HasDidSet : Base { override var stored: Int { didSet {} } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet06HasDidC0C6storedSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasDidSet): // CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet06HasDidC0C6storedSifg // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: store [[T1]] to [trivial] [[T2]] : $*Int // CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]] // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_T017materializeForSet06HasDidC0C6storedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasDidSet, @thick HasDidSet.Type) -> () // CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] // CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } override var computed: Int { get { return 0 } set(value) {} } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet06HasDidC0C8computedSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasDidSet): // CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet06HasDidC0C8computedSifg // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: store [[T1]] to [trivial] [[T2]] : $*Int // CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]] // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_T017materializeForSet06HasDidC0C8computedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasDidSet, @thick HasDidSet.Type) -> () // CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] // CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } } class HasStoredDidSet { var stored: Int = 0 { didSet {} } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet012HasStoredDidC0C6storedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasStoredDidSet, @thick HasStoredDidSet.Type) -> () { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*HasStoredDidSet, [[METATYPE:%.*]] : $@thick HasStoredDidSet.Type): // CHECK: [[SELF_VALUE:%.*]] = load_borrow [[SELF]] : $*HasStoredDidSet // CHECK: [[BUFFER_ADDR:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[VALUE:%.*]] = load [trivial] [[BUFFER_ADDR]] : $*Int // CHECK: [[SETTER_FN:%.*]] = function_ref @_T017materializeForSet012HasStoredDidC0C6storedSifs : $@convention(method) (Int, @guaranteed HasStoredDidSet) -> () // CHECK: apply [[SETTER_FN]]([[VALUE]], [[SELF_VALUE]]) : $@convention(method) (Int, @guaranteed HasStoredDidSet) -> () // CHECK: return // CHECK: } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet012HasStoredDidC0C6storedSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasStoredDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasStoredDidSet): // CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet012HasStoredDidC0C6storedSifg // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: store [[T1]] to [trivial] [[T2]] : $*Int // CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]] // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_T017materializeForSet012HasStoredDidC0C6storedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasStoredDidSet, @thick HasStoredDidSet.Type) -> () // CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] // CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } } class HasWeak { weak var weakvar: HasWeak? } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet7HasWeakC7weakvarACSgXwfm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasWeak) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasWeak): // CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Optional<HasWeak> // CHECK: [[T0:%.*]] = ref_element_addr [[SELF]] : $HasWeak, #HasWeak.weakvar // CHECK: [[T1:%.*]] = load_weak [[T0]] : $*@sil_weak Optional<HasWeak> // CHECK: store [[T1]] to [init] [[T2]] : $*Optional<HasWeak> // CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]] // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet7HasWeakC7weakvarACSgXwfmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasWeak, @thick HasWeak.Type) -> () // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, {{.*}} : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } // rdar://22109071 // Test that we don't use materializeForSet from a protocol extension. protocol Magic {} extension Magic { var hocus: Int { get { return 0 } set {} } } struct Wizard : Magic {} func improve(_ x: inout Int) {} func improveWizard(_ wizard: inout Wizard) { improve(&wizard.hocus) } // CHECK-LABEL: sil hidden @_T017materializeForSet13improveWizardyAA0E0VzF // CHECK: [[IMPROVE:%.*]] = function_ref @_T017materializeForSet7improveySizF : // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Int // Call the getter and materialize the result in the temporary. // CHECK-NEXT: [[T0:%.*]] = load [trivial] [[WIZARD:.*]] : $*Wizard // CHECK-NEXT: function_ref // CHECK-NEXT: [[GETTER:%.*]] = function_ref @_T017materializeForSet5MagicPAAE5hocusSifg // CHECK-NEXT: [[WTEMP:%.*]] = alloc_stack $Wizard // CHECK-NEXT: store [[T0]] to [trivial] [[WTEMP]] // CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]<Wizard>([[WTEMP]]) // CHECK-NEXT: dealloc_stack [[WTEMP]] // CHECK-NEXT: store [[T0]] to [trivial] [[TEMP]] // Call improve. // CHECK-NEXT: apply [[IMPROVE]]([[TEMP]]) // CHECK-NEXT: [[T0:%.*]] = load [trivial] [[TEMP]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T017materializeForSet5MagicPAAE5hocusSifs // CHECK-NEXT: apply [[SETTER]]<Wizard>([[T0]], [[WIZARD]]) // CHECK-NEXT: dealloc_stack [[TEMP]] protocol Totalled { var total: Int { get set } } struct Bill : Totalled { var total: Int } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet4BillV5totalSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Bill) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Bill): // CHECK: [[T0:%.*]] = struct_element_addr [[SELF]] : $*Bill, #Bill.total // CHECK: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer // CHECK: [[T3:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.none!enumelt // CHECK: [[T4:%.*]] = tuple ([[T1]] : $Builtin.RawPointer, [[T3]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } // CHECK-LABEL: sil private [transparent] [thunk] @_T017materializeForSet4BillVAA8TotalledA2aDP5totalSifmTW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Bill) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Bill): // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet4BillV5totalSifm // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[BUFFER]], [[STORAGE]], [[SELF]]) // CHECK-NEXT: [[LEFT:%.*]] = tuple_extract [[T1]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_extract [[T1]] // CHECK-NEXT: [[T1:%.*]] = tuple ([[LEFT]] : $Builtin.RawPointer, [[RIGHT]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: return [[T1]] : protocol AddressOnlySubscript { associatedtype Index subscript(i: Index) -> Index { get set } } struct Foo<T>: AddressOnlySubscript { subscript(i: T) -> T { get { return i } set { print("\(i) = \(newValue)") } } } func increment(_ x: inout Int) { x += 1 } // Generic subscripts. protocol GenericSubscriptProtocol { subscript<T>(_: T) -> T { get set } } struct GenericSubscriptWitness : GenericSubscriptProtocol { subscript<T>(_: T) -> T { get { } set { } } } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet23GenericSubscriptWitnessV9subscriptxxclufmytfU_ : $@convention(method) <T> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericSubscriptWitness, @thick GenericSubscriptWitness.Type) -> () { // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*GenericSubscriptWitness, %3 : $@thick GenericSubscriptWitness.Type): // CHECK: [[BUFFER:%.*]] = project_value_buffer $T in %1 : $*Builtin.UnsafeValueBuffer // CHECK-NEXT: [[INDICES:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*T // CHECK: [[SETTER:%.*]] = function_ref @_T017materializeForSet23GenericSubscriptWitnessV9subscriptxxclufs : $@convention(method) <τ_0_0> (@in τ_0_0, @in τ_0_0, @inout GenericSubscriptWitness) -> () // CHECK-NEXT: apply [[SETTER]]<T>([[INDICES]], [[BUFFER]], %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @in τ_0_0, @inout GenericSubscriptWitness) -> () // CHECK-NEXT: dealloc_value_buffer $*T in %1 : $*Builtin.UnsafeValueBuffer // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-LABEL sil hidden [transparent] [thunk] @_T017materializeForSet23GenericSubscriptWitnessVAA0dE8ProtocolA2aDP9subscriptqd__qd__clufmTW : $@convention(witness_method) <τ_0_0> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in τ_0_0, @inout GenericSubscriptWitness) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*T, %3 : $*GenericSubscriptWitness): // CHECK-NEXT: [[BUFFER:%.*]] = alloc_value_buffer $T in %1 : $*Builtin.UnsafeValueBuffer // CHECK-NEXT: copy_addr %2 to [initialization] [[BUFFER]] : $*T // CHECK-NEXT: [[VALUE:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*T // CHECK-NEXT: [[SELF:%.*]] = load [trivial] %3 : $*GenericSubscriptWitness // CHECK: [[GETTER:%.*]] = function_ref @_T017materializeForSet23GenericSubscriptWitnessV9subscriptxxclufg : $@convention(method) <τ_0_0> (@in τ_0_0, GenericSubscriptWitness) -> @out τ_0_0 // CHECK-NEXT: apply [[GETTER]]<T>([[VALUE]], %2, [[SELF]]) : $@convention(method) <τ_0_0> (@in τ_0_0, GenericSubscriptWitness) -> @out τ_0_0 // CHECK-NEXT: [[VALUE_PTR:%.*]] = address_to_pointer [[VALUE]] : $*T to $Builtin.RawPointer // CHECK: [[CALLBACK:%.*]] = function_ref @_T017materializeForSet23GenericSubscriptWitnessV9subscriptxxclufmytfU_ // CHECK-NEXT: [[CALLBACK_PTR:%.*]] = thin_function_to_pointer [[CALLBACK]] : $@convention(method) <τ_0_0> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericSubscriptWitness, @thick GenericSubscriptWitness.Type) -> () to $Builtin.RawPointer // CHECK-NEXT: [[CALLBACK_OPTIONAL:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_PTR]] : $Builtin.RawPointer // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[VALUE_PTR]] : $Builtin.RawPointer, [[CALLBACK_OPTIONAL]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: return [[RESULT]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) extension GenericSubscriptProtocol { subscript<T>(t: T) -> T { get { } set { } } } struct GenericSubscriptDefaultWitness : GenericSubscriptProtocol { } // Test for materializeForSet vs static properties of structs. protocol Beverage { static var abv: Int { get set } } struct Beer : Beverage { static var abv: Int { get { return 7 } set { } } } struct Wine<Color> : Beverage { static var abv: Int { get { return 14 } set { } } } // Make sure we can perform an inout access of such a property too. func inoutAccessOfStaticProperty<T : Beverage>(_ t: T.Type) { increment(&t.abv) } // Test for materializeForSet vs overridden computed property of classes. class BaseForOverride { var valueStored: Int var valueComputed: Int { get { } set { } } init(valueStored: Int) { self.valueStored = valueStored } } class DerivedForOverride : BaseForOverride { override var valueStored: Int { get { } set { } } override var valueComputed: Int { get { } set { } } } // Test for materializeForSet vs static properties of classes. class ReferenceBeer { class var abv: Int { get { return 7 } set { } } } func inoutAccessOfClassProperty() { increment(&ReferenceBeer.abv) } // Test for materializeForSet when Self is re-abstracted. // // We have to open-code the materializeForSelf witness, and not screw up // the re-abstraction. protocol Panda { var x: (Self) -> Self { get set } } func id<T>(_ t: T) -> T { return t } extension Panda { var x: (Self) -> Self { get { return id } set { } } } struct TuxedoPanda : Panda { } // CHECK-LABEL: sil private [transparent] @_T017materializeForSet11TuxedoPandaVAA0E0A2aDP1xxxcfmytfU_TW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout TuxedoPanda, @thick TuxedoPanda.Type) -> () // FIXME: Useless re-abstractions // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVACIxir_A2CIxyd_TR : $@convention(thin) (TuxedoPanda, @owned @callee_owned (@in TuxedoPanda) -> @out TuxedoPanda) -> TuxedoPanda // CHECK: function_ref @_T017materializeForSet5PandaPAAE1xxxcfs : $@convention(method) <τ_0_0 where τ_0_0 : Panda> (@owned @callee_owned (@in τ_0_0) -> @out τ_0_0, @inout τ_0_0) -> () // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVACIxyd_A2CIxir_TR : $@convention(thin) (@in TuxedoPanda, @owned @callee_owned (TuxedoPanda) -> TuxedoPanda) -> @out TuxedoPanda // CHECK: } // CHECK-LABEL: sil private [transparent] [thunk] @_T017materializeForSet11TuxedoPandaVAA0E0A2aDP1xxxcfmTW // Call the getter: // CHECK: function_ref @_T017materializeForSet5PandaPAAE1xxxcfg : $@convention(method) <τ_0_0 where τ_0_0 : Panda> (@in_guaranteed τ_0_0) -> @owned @callee_owned (@in τ_0_0) -> @out τ_0_0 // Result of calling the getter is re-abstracted to the maximally substituted type // by SILGenFunction::emitApply(): // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVACIxir_A2CIxyd_TR : $@convention(thin) (TuxedoPanda, @owned @callee_owned (@in TuxedoPanda) -> @out TuxedoPanda) -> TuxedoPanda // ... then we re-abstract to the requirement signature: // FIXME: Peephole this away with the previous one since there's actually no // abstraction change in this case. // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVACIxyd_A2CIxir_TR : $@convention(thin) (@in TuxedoPanda, @owned @callee_owned (TuxedoPanda) -> TuxedoPanda) -> @out TuxedoPanda // The callback: // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVAA0E0A2aDP1xxxcfmytfU_TW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout TuxedoPanda, @thick TuxedoPanda.Type) -> () // CHECK: } // Test for materializeForSet vs lazy properties of structs. struct LazyStructProperty { lazy var cat: Int = 5 } // CHECK-LABEL: sil hidden @_T017materializeForSet31inoutAccessOfLazyStructPropertyyAA0ghI0Vz1l_tF // CHECK: function_ref @_T017materializeForSet18LazyStructPropertyV3catSifg // CHECK: function_ref @_T017materializeForSet18LazyStructPropertyV3catSifs func inoutAccessOfLazyStructProperty(l: inout LazyStructProperty) { increment(&l.cat) } // Test for materializeForSet vs lazy properties of classes. // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet17LazyClassPropertyC3catSifm class LazyClassProperty { lazy var cat: Int = 5 } // CHECK-LABEL: sil hidden @_T017materializeForSet30inoutAccessOfLazyClassPropertyyAA0ghI0Cz1l_tF // CHECK: class_method {{.*}} : $LazyClassProperty, #LazyClassProperty.cat!materializeForSet.1 func inoutAccessOfLazyClassProperty(l: inout LazyClassProperty) { increment(&l.cat) } // Test for materializeForSet vs lazy properties of final classes. final class LazyFinalClassProperty { lazy var cat: Int = 5 } // CHECK-LABEL: sil hidden @_T017materializeForSet35inoutAccessOfLazyFinalClassPropertyyAA0ghiJ0Cz1l_tF // CHECK: function_ref @_T017materializeForSet22LazyFinalClassPropertyC3catSifg // CHECK: function_ref @_T017materializeForSet22LazyFinalClassPropertyC3catSifs func inoutAccessOfLazyFinalClassProperty(l: inout LazyFinalClassProperty) { increment(&l.cat) } // Make sure the below doesn't crash SILGen struct FooClosure { var computed: (((Int) -> Int) -> Int)? { get { return stored } set {} } var stored: (((Int) -> Int) -> Int)? = nil } // CHECK-LABEL: _T017materializeForSet22testMaterializedSetteryyF func testMaterializedSetter() { // CHECK: function_ref @_T017materializeForSet10FooClosureVACycfC var f = FooClosure() // CHECK: function_ref @_T017materializeForSet10FooClosureV8computedS3iccSgfg // CHECK: function_ref @_T017materializeForSet10FooClosureV8computedS3iccSgfs f.computed = f.computed } // CHECK-LABEL: sil_vtable DerivedForOverride { // CHECK: #BaseForOverride.valueStored!getter.1: (BaseForOverride) -> () -> Int : _T017materializeForSet07DerivedB8OverrideC11valueStoredSifg // CHECK: #BaseForOverride.valueStored!setter.1: (BaseForOverride) -> (Int) -> () : _T017materializeForSet07DerivedB8OverrideC11valueStoredSifs // CHECK: #BaseForOverride.valueStored!materializeForSet.1: (BaseForOverride) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) : _T017materializeForSet07DerivedB8OverrideC11valueStoredSifm // CHECK: #BaseForOverride.valueComputed!getter.1: (BaseForOverride) -> () -> Int : _T017materializeForSet07DerivedB8OverrideC13valueComputedSifg // CHECK: #BaseForOverride.valueComputed!setter.1: (BaseForOverride) -> (Int) -> () : _T017materializeForSet07DerivedB8OverrideC13valueComputedSifs // CHECK: #BaseForOverride.valueComputed!materializeForSet.1: (BaseForOverride) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) : _T017materializeForSet07DerivedB8OverrideC13valueComputedSifm // CHECK: } // CHECK-LABEL: sil_witness_table hidden Bill: Totalled module materializeForSet { // CHECK: method #Totalled.total!getter.1: {{.*}} : @_T017materializeForSet4BillVAA8TotalledA2aDP5totalSifgTW // CHECK: method #Totalled.total!setter.1: {{.*}} : @_T017materializeForSet4BillVAA8TotalledA2aDP5totalSifsTW // CHECK: method #Totalled.total!materializeForSet.1: {{.*}} : @_T017materializeForSet4BillVAA8TotalledA2aDP5totalSifmTW // CHECK: }
apache-2.0
15ada15b2a9c2bee6ecf75a833fab1c7
56.732657
334
0.673417
3.539052
false
false
false
false
iHunterX/SocketIODemo
DemoSocketIO/Utils/PAPermissions/Classes/Checks/PALocationPermissionsCheck.swift
1
1897
// // PALocationPermissionsCheck.swift // PAPermissionsApp // // Created by Pasquale Ambrosini on 06/09/16. // Copyright © 2016 Pasquale Ambrosini. All rights reserved. // import CoreLocation import UIKit public class PALocationPermissionsCheck: PAPermissionsCheck, CLLocationManagerDelegate { var requestAlwaysAuthorization : Bool { return Bundle.main.object(forInfoDictionaryKey: Constants.InfoPlistKeys.locationAlways) == nil ? false:true } fileprivate var locationManager = CLLocationManager() public override func checkStatus() { locationManager.delegate = self self.updateAuthorization() } public override func defaultAction() { if #available(iOS 8.0, *) { if CLLocationManager.authorizationStatus() == .denied { self.openSettings() }else{ if self.requestAlwaysAuthorization { self.locationManager.requestAlwaysAuthorization() }else{ self.locationManager.requestWhenInUseAuthorization() } self.updateStatus() } }else{ if CLLocationManager.authorizationStatus() == .denied { let settingsURL = URL(string: "prefs:root=LOCATION_SERVICES") UIApplication.shared.openURL(settingsURL!) }else{ self.status = .enabled self.updateStatus() } } } public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { self.updateAuthorization() } fileprivate func updateAuthorization() { let currentStatus = self.status if CLLocationManager.locationServicesEnabled() { switch(CLLocationManager.authorizationStatus()) { case .notDetermined, .restricted, .denied: self.status = PAPermissionsStatus.disabled case .authorizedAlways, .authorizedWhenInUse: self.status = PAPermissionsStatus.enabled } } else { self.status = PAPermissionsStatus.disabled } if self.status != currentStatus { self.updateStatus() } } }
gpl-3.0
5090b2ca74e71571f09c8eb2f1350f57
26.085714
114
0.739979
4.251121
false
false
false
false
tardieu/swift
test/SILGen/objc_bridging.swift
1
28473
// RUN: rm -rf %t && mkdir -p %t // RUN: %build-silgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-module -o %t -I %S/../Inputs/ObjCBridging %S/../Inputs/ObjCBridging/Appliances.swift // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -I %S/../Inputs/ObjCBridging -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-cpu --check-prefix=CHECK-%target-os-%target-cpu // REQUIRES: objc_interop import Foundation import Appliances func getDescription(_ o: NSObject) -> String { return o.description } // CHECK-LABEL: sil hidden @_TF13objc_bridging14getDescription // CHECK: bb0({{%.*}} : $NSObject): // CHECK: [[DESCRIPTION:%.*]] = class_method [volatile] {{%.*}} : {{.*}}, #NSObject.description!getter.1.foreign // CHECK: [[OPT_BRIDGED:%.*]] = apply [[DESCRIPTION]]({{%.*}}) // CHECK: select_enum [[OPT_BRIDGED]] // CHECK: [[BRIDGED:%.*]] = unchecked_enum_data [[OPT_BRIDGED]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]], // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]] // CHECK: [[NATIVE:%.*]] = unchecked_enum_data {{.*}} : $Optional<String> // CHECK: return [[NATIVE]] // CHECK:} func getUppercaseString(_ s: NSString) -> String { return s.uppercase() } // CHECK-LABEL: sil hidden @_TF13objc_bridging18getUppercaseString // CHECK: bb0({{%.*}} : $NSString): // -- The 'self' argument of NSString methods doesn't bridge. // CHECK-NOT: function_ref @_TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK-NOT: function_ref @swift_StringToNSString // CHECK: [[UPPERCASE_STRING:%.*]] = class_method [volatile] {{%.*}} : {{.*}}, #NSString.uppercase!1.foreign // CHECK: [[OPT_BRIDGED:%.*]] = apply [[UPPERCASE_STRING]]({{%.*}}) // CHECK: select_enum [[OPT_BRIDGED]] // CHECK: [[BRIDGED:%.*]] = unchecked_enum_data [[OPT_BRIDGED]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]] // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]] // CHECK: [[NATIVE:%.*]] = unchecked_enum_data {{.*}} : $Optional<String> // CHECK: return [[NATIVE]] // CHECK: } // @interface Foo -(void) setFoo: (NSString*)s; @end func setFoo(_ f: Foo, s: String) { var s = s f.setFoo(s) } // CHECK-LABEL: sil hidden @_TF13objc_bridging6setFoo // CHECK: bb0({{%.*}} : $Foo, {{%.*}} : $String): // CHECK: [[SET_FOO:%.*]] = class_method [volatile] [[F:%.*]] : {{.*}}, #Foo.setFoo!1.foreign // CHECK: [[NV:%.*]] = load // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NV]] // CHECK: select_enum [[OPT_NATIVE]] // CHECK: [[NATIVE:%.*]] = unchecked_enum_data [[OPT_NATIVE]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveCfT_CSo8NSString // CHECK: [[BORROWED_NATIVE:%.*]] = begin_borrow [[NATIVE]] // CHECK: [[BRIDGED:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_NATIVE]]) // CHECK: = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: end_borrow [[BORROWED_NATIVE]] from [[NATIVE]] // CHECK: bb3([[OPT_BRIDGED:%.*]] : $Optional<NSString>): // CHECK: apply [[SET_FOO]]([[OPT_BRIDGED]], %0) // CHECK: destroy_value [[OPT_BRIDGED]] // CHECK: } // @interface Foo -(BOOL) zim; @end func getZim(_ f: Foo) -> Bool { return f.zim() } // CHECK-ios-i386-LABEL: sil hidden @_TF13objc_bridging6getZim // CHECK-ios-i386: [[OBJC_BOOL:%.*]] = apply {{.*}} : $@convention(objc_method) (Foo) -> ObjCBool // CHECK-ios-i386: [[CONVERT:%.*]] = function_ref @swift_ObjCBoolToBool : $@convention(thin) (ObjCBool) -> Bool // CHECK-ios-i386: [[SWIFT_BOOL:%.*]] = apply [[CONVERT]]([[OBJC_BOOL]]) : $@convention(thin) (ObjCBool) -> Bool // CHECK-ios-i386: return [[SWIFT_BOOL]] : $Bool // CHECK-ios-i386: } // CHECK-watchos-i386-LABEL: sil hidden @_TF13objc_bridging6getZim // CHECK-watchos-i386: [[BOOL:%.*]] = apply {{.*}} : $@convention(objc_method) (Foo) -> Bool // CHECK-watchos-i386: return [[BOOL]] : $Bool // CHECK-watchos-i386: } // CHECK-macosx-x86_64-LABEL: sil hidden @_TF13objc_bridging6getZim // CHECK-macosx-x86_64: [[OBJC_BOOL:%.*]] = apply {{.*}} : $@convention(objc_method) (Foo) -> ObjCBool // CHECK-macosx-x86_64: [[CONVERT:%.*]] = function_ref @swift_ObjCBoolToBool : $@convention(thin) (ObjCBool) -> Bool // CHECK-macosx-x86_64: [[SWIFT_BOOL:%.*]] = apply [[CONVERT]]([[OBJC_BOOL]]) : $@convention(thin) (ObjCBool) -> Bool // CHECK-macosx-x86_64: return [[SWIFT_BOOL]] : $Bool // CHECK-macosx-x86_64: } // CHECK-ios-x86_64-LABEL: sil hidden @_TF13objc_bridging6getZim // CHECK-ios-x86_64: [[SWIFT_BOOL:%.*]] = apply {{.*}} : $@convention(objc_method) (Foo) -> Bool // CHECK-ios-x86_64: return [[SWIFT_BOOL]] : $Bool // CHECK-ios-x86_64: } // CHECK-arm64-LABEL: sil hidden @_TF13objc_bridging6getZim // CHECK-arm64: [[SWIFT_BOOL:%.*]] = apply {{.*}} : $@convention(objc_method) (Foo) -> Bool // CHECK-arm64: return [[SWIFT_BOOL]] : $Bool // CHECK-arm64: } // @interface Foo -(void) setZim: (BOOL)b; @end func setZim(_ f: Foo, b: Bool) { f.setZim(b) } // CHECK-ios-i386-LABEL: sil hidden @_TF13objc_bridging6setZim // CHECK-ios-i386: [[CONVERT:%.*]] = function_ref @swift_BoolToObjCBool : $@convention(thin) (Bool) -> ObjCBool // CHECK-ios-i386: [[OBJC_BOOL:%.*]] = apply [[CONVERT]]({{%.*}}) : $@convention(thin) (Bool) -> ObjCBool // CHECK-ios-i386: apply {{%.*}}([[OBJC_BOOL]], {{%.*}}) : $@convention(objc_method) (ObjCBool, Foo) -> () // CHECK-ios-i386: } // CHECK-macosx-x86_64-LABEL: sil hidden @_TF13objc_bridging6setZim // CHECK-macosx-x86_64: [[CONVERT:%.*]] = function_ref @swift_BoolToObjCBool : $@convention(thin) (Bool) -> ObjCBool // CHECK-macosx-x86_64: [[OBJC_BOOL:%.*]] = apply [[CONVERT]]({{%.*}}) : $@convention(thin) (Bool) -> ObjCBool // CHECK-macosx-x86_64: apply {{%.*}}([[OBJC_BOOL]], {{%.*}}) : $@convention(objc_method) (ObjCBool, Foo) -> () // CHECK-macosx-x86_64: } // CHECK-ios-x86_64-LABEL: sil hidden @_TF13objc_bridging6setZim // CHECK-ios-x86_64: bb0([[FOO_OBJ:%[0-9]+]] : $Foo, [[SWIFT_BOOL:%[0-9]+]] : $Bool): // CHECK-ios-x86_64: apply {{%.*}}([[SWIFT_BOOL]], [[FOO_OBJ]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK-ios-x86_64: } // CHECK-arm64-LABEL: sil hidden @_TF13objc_bridging6setZim // CHECK-arm64: bb0([[FOO_OBJ:%[0-9]+]] : $Foo, [[SWIFT_BOOL:%[0-9]+]] : $Bool): // CHECK-arm64: apply {{%.*}}([[SWIFT_BOOL]], [[FOO_OBJ]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK-arm64: } // CHECK-watchos-i386-LABEL: sil hidden @_TF13objc_bridging6setZim // CHECK-watchos-i386: bb0([[FOO_OBJ:%[0-9]+]] : $Foo, [[SWIFT_BOOL:%[0-9]+]] : $Bool): // CHECK-watchos-i386: apply {{%.*}}([[SWIFT_BOOL]], [[FOO_OBJ]]) : $@convention(objc_method) (Bool, Foo) -> () // CHECK-watchos-i386: } // @interface Foo -(_Bool) zang; @end func getZang(_ f: Foo) -> Bool { return f.zang() } // CHECK-LABEL: sil hidden @_TF13objc_bridging7getZangFCSo3FooSb // CHECK: [[BOOL:%.*]] = apply {{%.*}}(%0) : $@convention(objc_method) (Foo) -> Bool // CHECK: return [[BOOL]] // @interface Foo -(void) setZang: (_Bool)b; @end func setZang(_ f: Foo, _ b: Bool) { f.setZang(b) } // CHECK-LABEL: sil hidden @_TF13objc_bridging7setZangFTCSo3FooSb_T_ // CHECK: apply {{%.*}}(%1, %0) : $@convention(objc_method) (Bool, Foo) -> () // NSString *bar(void); func callBar() -> String { return bar() } // CHECK-LABEL: sil hidden @_TF13objc_bridging7callBar // CHECK: bb0: // CHECK: [[BAR:%.*]] = function_ref @bar // CHECK: [[OPT_BRIDGED:%.*]] = apply [[BAR]]() // CHECK: select_enum [[OPT_BRIDGED]] // CHECK: [[BRIDGED:%.*]] = unchecked_enum_data [[OPT_BRIDGED]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: [[BRIDGED_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: [[NATIVE:%.*]] = apply [[NSSTRING_TO_STRING]]([[BRIDGED_BOX]] // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NATIVE]] // CHECK: [[NATIVE:%.*]] = unchecked_enum_data {{.*}} : $Optional<String> // CHECK: return [[NATIVE]] // CHECK: } // void setBar(NSString *s); func callSetBar(_ s: String) { var s = s setBar(s) } // CHECK-LABEL: sil hidden @_TF13objc_bridging10callSetBar // CHECK: bb0({{%.*}} : $String): // CHECK: [[SET_BAR:%.*]] = function_ref @setBar // CHECK: [[NV:%.*]] = load // CHECK: [[OPT_NATIVE:%.*]] = enum $Optional<String>, #Optional.some!enumelt.1, [[NV]] // CHECK: select_enum [[OPT_NATIVE]] // CHECK: [[NATIVE:%.*]] = unchecked_enum_data [[OPT_NATIVE]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveCfT_CSo8NSString // CHECK: [[BORROWED_NATIVE:%.*]] = begin_borrow [[NATIVE]] // CHECK: [[BRIDGED:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_NATIVE]]) // CHECK: = enum $Optional<NSString>, #Optional.some!enumelt.1, [[BRIDGED]] // CHECK: end_borrow [[BORROWED_NATIVE]] from [[NATIVE]] // CHECK: bb3([[OPT_BRIDGED:%.*]] : $Optional<NSString>): // CHECK: apply [[SET_BAR]]([[OPT_BRIDGED]]) // CHECK: destroy_value [[OPT_BRIDGED]] // CHECK: } var NSS: NSString // -- NSString methods don't convert 'self' extension NSString { var nsstrFakeProp: NSString { get { return NSS } set {} } // CHECK-LABEL: sil hidden [thunk] @_TToFE13objc_bridgingCSo8NSStringg13nsstrFakePropS0_ // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: } // CHECK-LABEL: sil hidden [thunk] @_TToFE13objc_bridgingCSo8NSStrings13nsstrFakePropS0_ // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: } func nsstrResult() -> NSString { return NSS } // CHECK-LABEL: sil hidden [thunk] @_TToFE13objc_bridgingCSo8NSString11nsstrResult // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: } func nsstrArg(_ s: NSString) { } // CHECK-LABEL: sil hidden [thunk] @_TToFE13objc_bridgingCSo8NSString8nsstrArg // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: } } class Bas : NSObject { // -- Bridging thunks for String properties convert between NSString var strRealProp: String = "Hello" // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Basg11strRealPropSS : $@convention(objc_method) (Bas) -> @autoreleased NSString { // CHECK: bb0([[THIS:%.*]] : $Bas): // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] : $Bas // CHECK: // function_ref objc_bridging.Bas.strRealProp.getter // CHECK: [[PROPIMPL:%.*]] = function_ref @_TFC13objc_bridging3Basg11strRealPropSS // CHECK: [[PROP_COPY:%.*]] = apply [[PROPIMPL]]([[THIS_COPY]]) : $@convention(method) (@guaranteed Bas) -> @owned String // CHECK: destroy_value [[THIS_COPY]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveCfT_CSo8NSString // CHECK: [[BORROWED_PROP_COPY:%.*]] = begin_borrow [[PROP_COPY]] // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_PROP_COPY]]) // CHECK: end_borrow [[BORROWED_PROP_COPY]] from [[PROP_COPY]] // CHECK: destroy_value [[PROP_COPY]] // CHECK: return [[NSSTR]] // CHECK: } // CHECK-LABEL: sil hidden @_TFC13objc_bridging3Basg11strRealPropSS // CHECK: [[PROP_ADDR:%.*]] = ref_element_addr %0 : {{.*}}, #Bas.strRealProp // CHECK: [[PROP:%.*]] = load [copy] [[PROP_ADDR]] // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bass11strRealPropSS : $@convention(objc_method) (NSString, Bas) -> () { // CHECK: bb0([[VALUE:%.*]] : $NSString, [[THIS:%.*]] : $Bas): // CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: [[VALUE_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[VALUE_COPY]] // CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[VALUE_BOX]] // CHECK: [[SETIMPL:%.*]] = function_ref @_TFC13objc_bridging3Bass11strRealPropSS // CHECK: apply [[SETIMPL]]([[STR]], [[THIS_COPY]]) // CHECK: destroy_value [[THIS_COPY]] // CHECK: } // end sil function '_TToFC13objc_bridging3Bass11strRealPropSS' // CHECK-LABEL: sil hidden @_TFC13objc_bridging3Bass11strRealPropSS // CHECK: bb0(%0 : $String, %1 : $Bas): // CHECK: [[STR_ADDR:%.*]] = ref_element_addr %1 : {{.*}}, #Bas.strRealProp // CHECK: assign {{.*}} to [[STR_ADDR]] // CHECK: } var strFakeProp: String { get { return "" } set {} } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Basg11strFakePropSS : $@convention(objc_method) (Bas) -> @autoreleased NSString { // CHECK: bb0([[THIS:%.*]] : $Bas): // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[GETTER:%.*]] = function_ref @_TFC13objc_bridging3Basg11strFakePropSS // CHECK: [[STR:%.*]] = apply [[GETTER]]([[THIS_COPY]]) // CHECK: destroy_value [[THIS_COPY]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveCfT_CSo8NSString // CHECK: [[BORROWED_STR:%.*]] = begin_borrow [[STR]] // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STR]]) // CHECK: end_borrow [[BORROWED_STR]] from [[STR]] // CHECK: destroy_value [[STR]] // CHECK: return [[NSSTR]] // CHECK: } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bass11strFakePropSS : $@convention(objc_method) (NSString, Bas) -> () { // CHECK: bb0([[NSSTR:%.*]] : $NSString, [[THIS:%.*]] : $Bas): // CHECK: [[NSSTR_COPY:%.*]] = copy_value [[NSSTR]] // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR_COPY]] // CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[NSSTR_BOX]] // CHECK: [[SETTER:%.*]] = function_ref @_TFC13objc_bridging3Bass11strFakePropSS // CHECK: apply [[SETTER]]([[STR]], [[THIS_COPY]]) // CHECK: destroy_value [[THIS_COPY]] // CHECK: } // end sil function '_TToFC13objc_bridging3Bass11strFakePropSS' // -- Bridging thunks for explicitly NSString properties don't convert var nsstrRealProp: NSString var nsstrFakeProp: NSString { get { return NSS } set {} } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Basg13nsstrRealPropCSo8NSString : $@convention(objc_method) (Bas) -> @autoreleased NSString { // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bass13nsstrRealPropCSo8NSString : $@convention(objc_method) (NSString, Bas) -> // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: } // -- Bridging thunks for String methods convert between NSString func strResult() -> String { return "" } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bas9strResult // CHECK: bb0([[THIS:%.*]] : $Bas): // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[METHOD:%.*]] = function_ref @_TFC13objc_bridging3Bas9strResult // CHECK: [[STR:%.*]] = apply [[METHOD]]([[THIS_COPY]]) // CHECK: destroy_value [[THIS_COPY]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveCfT_CSo8NSString // CHECK: [[BORROWED_STR:%.*]] = begin_borrow [[STR]] // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STR]]) // CHECK: end_borrow [[BORROWED_STR]] from [[STR]] // CHECK: destroy_value [[STR]] // CHECK: return [[NSSTR]] // CHECK: } func strArg(_ s: String) { } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bas6strArg // CHECK: bb0([[NSSTR:%.*]] : $NSString, [[THIS:%.*]] : $Bas): // CHECK: [[NSSTR_COPY:%.*]] = copy_value [[NSSTR]] // CHECK: [[THIS_COPY:%.*]] = copy_value [[THIS]] // CHECK: [[NSSTRING_TO_STRING:%.*]] = function_ref @_TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR_COPY]] // CHECK: [[STR:%.*]] = apply [[NSSTRING_TO_STRING]]([[NSSTR_BOX]] // CHECK: [[METHOD:%.*]] = function_ref @_TFC13objc_bridging3Bas6strArg // CHECK: apply [[METHOD]]([[STR]], [[THIS_COPY]]) // CHECK: destroy_value [[THIS_COPY]] // CHECK: } // end sil function '_TToFC13objc_bridging3Bas6strArgfSST_' // -- Bridging thunks for explicitly NSString properties don't convert func nsstrResult() -> NSString { return NSS } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bas11nsstrResult // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: } func nsstrArg(_ s: NSString) { } // CHECK-LABEL: sil hidden @_TFC13objc_bridging3Bas8nsstrArg // CHECK-NOT: swift_StringToNSString // CHECK-NOT: _TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: } init(str: NSString) { nsstrRealProp = str super.init() } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bas8arrayArg{{.*}} : $@convention(objc_method) (NSArray, Bas) -> () // CHECK: bb0([[NSARRAY:%[0-9]+]] : $NSArray, [[SELF:%[0-9]+]] : $Bas): // CHECK: [[NSARRAY_COPY:%.*]] = copy_value [[NSARRAY]] : $NSArray // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Bas // CHECK: [[CONV_FN:%[0-9]+]] = function_ref @_TZFE10FoundationSa36_unconditionallyBridgeFromObjectiveCfGSqCSo7NSArray_GSax_ // CHECK: [[OPT_NSARRAY:%[0-9]+]] = enum $Optional<NSArray>, #Optional.some!enumelt.1, [[NSARRAY_COPY]] : $NSArray // CHECK: [[ARRAY_META:%[0-9]+]] = metatype $@thin Array<AnyObject>.Type // CHECK: [[ARRAY:%[0-9]+]] = apply [[CONV_FN]]<AnyObject>([[OPT_NSARRAY]], [[ARRAY_META]]) // CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_TFC13objc_bridging3Bas{{.*}} : $@convention(method) (@owned Array<AnyObject>, @guaranteed Bas) -> () // CHECK: [[RESULT:%[0-9]+]] = apply [[SWIFT_FN]]([[ARRAY]], [[SELF_COPY]]) : $@convention(method) (@owned Array<AnyObject>, @guaranteed Bas) -> () // CHECK: destroy_value [[SELF_COPY]] : $Bas // CHECK: return [[RESULT]] : $() func arrayArg(_ array: [AnyObject]) { } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bas11arrayResult{{.*}} : $@convention(objc_method) (Bas) -> @autoreleased NSArray // CHECK: bb0([[SELF:%[0-9]+]] : $Bas): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Bas // CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_TFC13objc_bridging3Bas11arrayResult{{.*}} : $@convention(method) (@guaranteed Bas) -> @owned Array<AnyObject> // CHECK: [[ARRAY:%[0-9]+]] = apply [[SWIFT_FN]]([[SELF_COPY]]) : $@convention(method) (@guaranteed Bas) -> @owned Array<AnyObject> // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[CONV_FN:%[0-9]+]] = function_ref @_TFE10FoundationSa19_bridgeToObjectiveCfT_CSo7NSArray // CHECK: [[BORROWED_ARRAY:%.*]] = begin_borrow [[ARRAY]] // CHECK: [[NSARRAY:%[0-9]+]] = apply [[CONV_FN]]<AnyObject>([[BORROWED_ARRAY]]) : $@convention(method) <τ_0_0> (@guaranteed Array<τ_0_0>) -> @owned NSArray // CHECK: end_borrow [[BORROWED_ARRAY]] from [[ARRAY]] // CHECK: destroy_value [[ARRAY]] // CHECK: return [[NSARRAY]] func arrayResult() -> [AnyObject] { return [] } // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Basg9arrayPropGSaSS_ : $@convention(objc_method) (Bas) -> @autoreleased NSArray // CHECK-LABEL: sil hidden [thunk] @_TToFC13objc_bridging3Bass9arrayPropGSaSS_ : $@convention(objc_method) (NSArray, Bas) -> () var arrayProp: [String] = [] } // CHECK-LABEL: sil hidden @_TF13objc_bridging16applyStringBlock{{.*}} : func applyStringBlock(_ f: @convention(block) (String) -> String, x: String) -> String { // CHECK: bb0([[BLOCK:%.*]] : $@convention(block) (NSString) -> @autoreleased NSString, [[STRING:%.*]] : $String): // CHECK: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK: [[BLOCK_COPY_COPY:%.*]] = copy_value [[BLOCK_COPY]] // CHECK: [[STRING_COPY:%.*]] = copy_value [[STRING]] // CHECK: [[STRING_TO_NSSTRING:%.*]] = function_ref @_TFE10FoundationSS19_bridgeToObjectiveCfT_CSo8NSString // CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]] // CHECK: [[NSSTR:%.*]] = apply [[STRING_TO_NSSTRING]]([[BORROWED_STRING_COPY]]) : $@convention(method) (@guaranteed String) // CHECK: [[RESULT_NSSTR:%.*]] = apply [[BLOCK_COPY_COPY]]([[NSSTR]]) : $@convention(block) (NSString) -> @autoreleased NSString // CHECK: [[FINAL_BRIDGE:%.*]] = function_ref @_TZFE10FoundationSS36_unconditionallyBridgeFromObjectiveCfGSqCSo8NSString_SS // CHECK: [[OPTIONAL_NSSTR:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[RESULT_NSSTR]] // CHECK: [[RESULT:%.*]] = apply [[FINAL_BRIDGE]]([[OPTIONAL_NSSTR]], {{.*}}) : $@convention(method) (@owned Optional<NSString>, @thin String.Type) -> @owned String // CHECK: destroy_value [[NSSTR]] // CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]] // CHECK: destroy_value [[STRING_COPY]] // CHECK: destroy_value [[BLOCK_COPY_COPY]] // CHECK: destroy_value [[STRING]] // CHECK: destroy_value [[BLOCK_COPY]] // CHECK: destroy_value [[BLOCK]] // CHECK: return [[RESULT]] : $String return f(x) } // CHECK: } // end sil function '_TF13objc_bridging16applyStringBlock{{.*}}' // CHECK-LABEL: sil hidden @_TF13objc_bridging15bridgeCFunction func bridgeCFunction() -> (String!) -> (String!) { // CHECK: [[THUNK:%.*]] = function_ref @_TTOFSC18NSStringFromStringFGSQSS_GSQSS_ : $@convention(thin) (@owned Optional<String>) -> @owned Optional<String> // CHECK: [[THICK:%.*]] = thin_to_thick_function [[THUNK]] // CHECK: return [[THICK]] return NSStringFromString } func forceNSArrayMembers() -> (NSArray, NSArray) { let x = NSArray(objects: nil, count: 0) return (x, x) } // Check that the allocating initializer shim for initializers that take pointer // arguments lifetime-extends the bridged pointer for the right duration. // <rdar://problem/16738050> // CHECK-LABEL: sil shared @_TFCSo7NSArrayC // CHECK: [[SELF:%.*]] = alloc_ref_dynamic // CHECK: [[METHOD:%.*]] = function_ref @_TTOFCSo7NSArrayc // CHECK: [[RESULT:%.*]] = apply [[METHOD]] // CHECK: return [[RESULT]] // Check that type lowering preserves the bool/BOOL distinction when bridging // imported C functions. // CHECK-ios-i386-LABEL: sil hidden @_TF13objc_bridging5boolsFSbTSbSb_ // CHECK-ios-i386: function_ref @useBOOL : $@convention(c) (ObjCBool) -> () // CHECK-ios-i386: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-ios-i386: function_ref @getBOOL : $@convention(c) () -> ObjCBool // CHECK-ios-i386: function_ref @getBool : $@convention(c) () -> Bool // CHECK-macosx-x86_64-LABEL: sil hidden @_TF13objc_bridging5boolsFSbTSbSb_ // CHECK-macosx-x86_64: function_ref @useBOOL : $@convention(c) (ObjCBool) -> () // CHECK-macosx-x86_64: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-macosx-x86_64: function_ref @getBOOL : $@convention(c) () -> ObjCBool // CHECK-macosx-x86_64: function_ref @getBool : $@convention(c) () -> Bool // FIXME: no distinction on x86_64, arm64 or watchos-i386, since SILGen looks // at the underlying Clang decl of the bridged decl to decide whether it needs // bridging. // // CHECK-watchos-i386-LABEL: sil hidden @_TF13objc_bridging5boolsFSbTSbSb_ // CHECK-watchos-i386: function_ref @useBOOL : $@convention(c) (Bool) -> () // CHECK-watchos-i386: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-watchos-i386: function_ref @getBOOL : $@convention(c) () -> Bool // CHECK-watchos-i386: function_ref @getBool : $@convention(c) () -> Bool // CHECK-ios-x86_64-LABEL: sil hidden @_TF13objc_bridging5boolsFSbTSbSb_ // CHECK-ios-x86_64: function_ref @useBOOL : $@convention(c) (Bool) -> () // CHECK-ios-x86_64: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-ios-x86_64: function_ref @getBOOL : $@convention(c) () -> Bool // CHECK-ios-x86_64: function_ref @getBool : $@convention(c) () -> Bool // CHECK-arm64-LABEL: sil hidden @_TF13objc_bridging5boolsFSbTSbSb_ // CHECK-arm64: function_ref @useBOOL : $@convention(c) (Bool) -> () // CHECK-arm64: function_ref @useBool : $@convention(c) (Bool) -> () // CHECK-arm64: function_ref @getBOOL : $@convention(c) () -> Bool // CHECK-arm64: function_ref @getBool : $@convention(c) () -> Bool func bools(_ x: Bool) -> (Bool, Bool) { useBOOL(x) useBool(x) return (getBOOL(), getBool()) } // CHECK-LABEL: sil hidden @_TF13objc_bridging9getFridge // CHECK: bb0([[HOME:%[0-9]+]] : $APPHouse): func getFridge(_ home: APPHouse) -> Refrigerator { // CHECK: [[GETTER:%[0-9]+]] = class_method [volatile] [[HOME]] : $APPHouse, #APPHouse.fridge!getter.1.foreign // CHECK: [[OBJC_RESULT:%[0-9]+]] = apply [[GETTER]]([[HOME]]) // CHECK: [[BRIDGE_FN:%[0-9]+]] = function_ref @_TZFV10Appliances12Refrigerator36_unconditionallyBridgeFromObjectiveC // CHECK: [[REFRIGERATOR_META:%[0-9]+]] = metatype $@thin Refrigerator.Type // CHECK: [[RESULT:%[0-9]+]] = apply [[BRIDGE_FN]]([[OBJC_RESULT]], [[REFRIGERATOR_META]]) // CHECK: destroy_value [[HOME]] : $APPHouse // CHECK: return [[RESULT]] : $Refrigerator return home.fridge } // CHECK-LABEL: sil hidden @_TF13objc_bridging16updateFridgeTemp // CHECK: bb0([[HOME:%[0-9]+]] : $APPHouse, [[DELTA:%[0-9]+]] : $Double): func updateFridgeTemp(_ home: APPHouse, delta: Double) { // += // CHECK: [[PLUS_EQ:%[0-9]+]] = function_ref @_TFsoi2peFTRSdSd_T_ // Borrowed home // CHECK: [[BORROWED_HOME:%.*]] = begin_borrow [[HOME]] // Temporary fridge // CHECK: [[TEMP_FRIDGE:%[0-9]+]] = alloc_stack $Refrigerator // Get operation // CHECK: [[GETTER:%[0-9]+]] = class_method [volatile] [[BORROWED_HOME]] : $APPHouse, #APPHouse.fridge!getter.1.foreign // CHECK: [[OBJC_FRIDGE:%[0-9]+]] = apply [[GETTER]]([[BORROWED_HOME]]) // CHECK: [[BRIDGE_FROM_FN:%[0-9]+]] = function_ref @_TZFV10Appliances12Refrigerator36_unconditionallyBridgeFromObjectiveC // CHECK: [[REFRIGERATOR_META:%[0-9]+]] = metatype $@thin Refrigerator.Type // CHECK: [[FRIDGE:%[0-9]+]] = apply [[BRIDGE_FROM_FN]]([[OBJC_FRIDGE]], [[REFRIGERATOR_META]]) // End the borrow from the get operation. // CHECK: end_borrow [[BORROWED_HOME]] from [[HOME]] // Addition // CHECK: [[TEMP:%[0-9]+]] = struct_element_addr [[TEMP_FRIDGE]] : $*Refrigerator, #Refrigerator.temperature // CHECK: apply [[PLUS_EQ]]([[TEMP]], [[DELTA]]) // Setter // CHECK: [[FRIDGE:%[0-9]+]] = load [trivial] [[TEMP_FRIDGE]] : $*Refrigerator // CHECK: [[SETTER:%[0-9]+]] = class_method [volatile] [[HOME]] : $APPHouse, #APPHouse.fridge!setter.1.foreign // CHECK: [[BRIDGE_TO_FN:%[0-9]+]] = function_ref @_TFV10Appliances12Refrigerator19_bridgeToObjectiveCfT_CSo15APPRefrigerator // CHECK: [[OBJC_ARG:%[0-9]+]] = apply [[BRIDGE_TO_FN]]([[FRIDGE]]) // CHECK: apply [[SETTER]]([[OBJC_ARG]], [[HOME]]) : $@convention(objc_method) (APPRefrigerator, APPHouse) -> () // CHECK: destroy_value [[OBJC_ARG]] // CHECK: destroy_value [[HOME]] home.fridge.temperature += delta }
apache-2.0
8497abf829ed6b68eb330d9660f85775
52.718868
247
0.635945
3.396278
false
false
false
false
LamGiauKhongKhoTeam/LGKK
Modules/FlagKit/FlagKit.swift
1
6431
// // FlagKit.swift // MobileTrading // // Created by Nguyen Minh on 4/6/17. // Copyright © 2017 AHDEnglish. All rights reserved. // import UIKit import Foundation import CoreGraphics open class SpriteSheet { typealias GridSize = (cols: Int, rows: Int) typealias ImageSize = (width: CGFloat, height: CGFloat) typealias Margin = (top: CGFloat, left: CGFloat, right: CGFloat, bottom: CGFloat) struct SheetInfo { fileprivate(set) var gridSize: GridSize fileprivate(set) var spriteSize: ImageSize fileprivate(set) var spriteMargin: Margin fileprivate(set) var codes: [String] } fileprivate(set) var info: SheetInfo fileprivate(set) var image: UIImage fileprivate var imageCache = [String:UIImage]() init?(sheetImage: UIImage, info sInfo: SheetInfo) { image = sheetImage info = sInfo } func getImageFor(code: String) -> UIImage? { var cimg: UIImage? cimg = imageCache[code] if cimg == nil { let rect = getRectFor(code) cimg = image.cropped(to: rect) cimg = image.cropped(to: rect) imageCache[code] = cimg } return cimg } open func getRectFor(_ code: String) -> CGRect { let spriteW = info.spriteSize.width let spriteH = info.spriteSize.height let realSpriteW = spriteW - info.spriteMargin.left - info.spriteMargin.right let realSpriteH = spriteH - info.spriteMargin.top - info.spriteMargin.bottom let idx = info.codes.index(of: code.lowercased()) ?? 0 let dx = idx % info.gridSize.cols let dy = idx/info.gridSize.cols let x = CGFloat(dx) * spriteW + info.spriteMargin.top let y = CGFloat(dy) * spriteH + info.spriteMargin.left return CGRect(x: x, y: y, width: realSpriteW, height: realSpriteH) } deinit { imageCache.removeAll() } } open class FlagKit: NSObject { static let shared = FlagKit() var spriteSheet: SpriteSheet? override init() { super.init() spriteSheet = FlagKit.loadDefault() } open class func loadDefault() -> SpriteSheet? { guard let assetsBundle = assetsBundle() else { return nil } if let infoFile = assetsBundle.path(forResource: "flags_v1", ofType: "json") { return self.loadSheetFrom(infoFile) } return nil } open class func loadSheetFrom(_ file: String) -> SpriteSheet? { guard let assetsBundle = assetsBundle() else { return nil } if let infoData = try? Data(contentsOf: URL(fileURLWithPath: file)) { do { if let infoObj = try JSONSerialization.jsonObject(with: infoData, options: JSONSerialization.ReadingOptions(rawValue: 0)) as? [String:Any] { if let gridSizeObj = infoObj["gridSize"] as? [String:Int], let spriteSizeObj = infoObj["spriteSize"] as? [String:CGFloat], let spriteMarginObj = infoObj["margin"] as? [String:CGFloat] { let gridSize = (gridSizeObj["cols"]!, gridSizeObj["rows"]!) let spriteSize = (spriteSizeObj["width"]!, spriteSizeObj["height"]!) let spriteMargin = (spriteMarginObj["top"]!, spriteMarginObj["left"]!, spriteMarginObj["right"]!, spriteMarginObj["bottom"]!) if let codes = (infoObj["codes"] as? String)?.components(separatedBy: ",") { if let sheetFileName = infoObj["sheetFile"] as? String, let resourceUrl = assetsBundle.resourceURL { let sheetFileUrl = resourceUrl.appendingPathComponent(sheetFileName) if let image = UIImage(contentsOfFile: sheetFileUrl.path) { let info = SpriteSheet.SheetInfo(gridSize: gridSize, spriteSize: spriteSize, spriteMargin: spriteMargin, codes: codes) return SpriteSheet(sheetImage: image, info: info) } } } } } } catch { } } return nil } fileprivate class func assetsBundle() -> Bundle? { let bundle = Bundle(for: self) guard let assetsBundlePath = bundle.path(forResource: "flag-assets", ofType: "bundle") else { return nil } return Bundle(path: assetsBundlePath); } } extension UIImage { enum JPEGQuality: CGFloat { case lowest = 0 case low = 0.25 case medium = 0.5 case high = 0.75 case highest = 1 } /// Returns the data for the specified image in PNG format /// If the image object’s underlying image data has been purged, calling this function forces that data to be reloaded into memory. /// - returns: A data object containing the PNG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format. var png: Data? { return UIImagePNGRepresentation(self) } /// Returns the data for the specified image in JPEG format. /// If the image object’s underlying image data has been purged, calling this function forces that data to be reloaded into memory. /// - returns: A data object containing the JPEG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format. func jpeg(_ quality: JPEGQuality) -> Data? { return UIImageJPEGRepresentation(self, quality.rawValue) } /// UIImage Cropped to CGRect. /// /// - Parameter rect: CGRect to crop UIImage to. /// - Returns: cropped UIImage public func cropped(to rect: CGRect) -> UIImage { guard rect.size.height < size.height && rect.size.width < size.width else { return self } guard let image: CGImage = cgImage?.cropping(to: rect) else { return self } return UIImage(cgImage: image) } }
mit
941188dc8552b1233d807572d3bdde7c
38.913043
242
0.59197
4.59
false
false
false
false
cpimhoff/AntlerKit
Framework/AntlerKit/Aliases.swift
1
787
// // Aliases.swift // AntlerKit // // Created by Charlie Imhoff on 12/31/16. // Copyright © 2016 Charlie Imhoff. All rights reserved. // import Foundation import SpriteKit import GameplayKit // Geometry public typealias Point = CGPoint public typealias Vector = CGVector public typealias Size = CGSize // SpriteKit public typealias Primitive = SKNode public typealias PhysicsBody = SKPhysicsBody public typealias Color = SKColor // GameplayKit public typealias Agent = GKAgent public typealias Agent2D = GKAgent2D public typealias RuleSystem = GKRuleSystem public typealias Rule = GKRule // Cross Platform #if os(iOS) internal typealias View = UIView public typealias Rect = CGRect #elseif os(macOS) internal typealias View = NSView public typealias Rect = NSRect #endif
mit
b3d518e0e0195eae5ba8d818e77c651c
20.243243
57
0.774809
4.09375
false
false
false
false
linbin00303/Dotadog
DotaDog/DotaDog/Classes/Match/DDogMatchHttp.swift
1
867
// // DDogMatchHttp.swift // DotaDog // // Created by 林彬 on 16/6/2. // Copyright © 2016年 linbin. All rights reserved. // import UIKit import MJExtension class DDogMatchHttp: NSObject { class func getMatchNetDataByUrl( time : String , matchMs : (resultMs : NSMutableArray?) -> ()) { LBNetWorkTool.shareNetWorkTool.request(.GET, urlString: "http://api.live.uuu9.com/Index/deafult.html?cid=1&lastdate=\(time)&t=1&k=", parameters: nil) { (result, error) -> () in if result == nil { matchMs(resultMs: nil) return } let tempArr = result!["output"] as! NSArray let models = DDogCompetitionModel.mj_objectArrayWithKeyValuesArray(tempArr) matchMs(resultMs: models) } } }
mit
b80f396d5bccf13acf5f65f9cb5cf9f4
29.714286
188
0.560465
4.056604
false
false
false
false
midoks/Swift-Learning
EampleApp/EampleApp/Controllers/User/UserLoginViewController.swift
1
5853
// // UserLoginViewController.swift // // Created by midoks on 15/7/20. // Copyright © 2015年 midoks. All rights reserved. // import UIKit class UserLoginViewController: UIViewController, UITextFieldDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. initNav() initLoginPage() } //初始化导航 func initNav(){ let leftButton = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.plain, target: self, action: #selector(UserLoginViewController.close(_:))) let rightButton = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.plain, target: self, action: #selector(UserLoginViewController.register)) self.navigationItem.leftBarButtonItem = leftButton self.navigationItem.rightBarButtonItem = rightButton //取tableview的背静颜色 self.view.backgroundColor = UIColor(red: 239/255, green: 239/255, blue: 244/255, alpha: 1) self.title = "登录" } //初始化页面 func initLoginPage(){ let xCenter = self.view.bounds.size.width/2 //let firstHight = 44 + 20 //用户左边的提示 let userNameLeft = UILabel(frame: CGRect(x: 0, y: 0, width: 60, height: 40)) userNameLeft.textAlignment = NSTextAlignment.center //userNameLeft.backgroundColor = UIColor.redColor() userNameLeft.text = "账户" //用户名输入 let userName = UITextField(frame: CGRect(x: 0, y: 100, width: self.view.bounds.size.width * 0.8, height: 40)) userName.center = CGPoint(x: xCenter, y: 100) userName.keyboardType = UIKeyboardType.twitter userName.borderStyle = UITextBorderStyle.none userName.textAlignment = NSTextAlignment.left userName.clearButtonMode = UITextFieldViewMode.whileEditing userName.returnKeyType = UIReturnKeyType.done userName.placeholder = "请输入你的账户" userName.leftView = userNameLeft userName.leftViewMode = UITextFieldViewMode.always userName.delegate = self userName.backgroundColor = UIColor.white self.view.addSubview(userName) //密码左边的提示 let userPwdLeft = UILabel(frame: CGRect(x: 0, y: 0, width: 60, height: 40)) userPwdLeft.textAlignment = NSTextAlignment.center userPwdLeft.text = "密码" let tool = setInputUIToolbar() //用户密码输入 let userPwd = UITextField(frame: CGRect(x: 0, y: 141, width: self.view.bounds.size.width * 0.8, height: 40)) userPwd.center = CGPoint(x: xCenter, y: 141) userPwd.keyboardType = UIKeyboardType.namePhonePad userPwd.borderStyle = UITextBorderStyle.none userPwd.textAlignment = NSTextAlignment.left userPwd.clearButtonMode = UITextFieldViewMode.whileEditing userPwd.returnKeyType = UIReturnKeyType.done userPwd.placeholder = "请输入你的密码" userPwd.isSecureTextEntry = true userPwd.leftView = userPwdLeft userPwd.leftViewMode = UITextFieldViewMode.always //自定义工具栏 userPwd.inputAccessoryView = tool userPwd.delegate = self userPwd.backgroundColor = UIColor.white self.view.addSubview(userPwd) //登录按钮 let loginButton = UIButton(frame: CGRect(x: 0, y: 182, width: self.view.bounds.size.width * 0.8, height: 40)) loginButton.center = CGPoint(x: xCenter, y: 182) loginButton.setTitle("登录", for: UIControlState()) loginButton.setTitleColor(UIColor.blue, for: UIControlState()) loginButton.setTitleColor(UIColor.brown, for: UIControlState.highlighted) loginButton.addTarget(self, action: #selector(UserLoginViewController.close(_:)), for: UIControlEvents.touchUpInside) self.view.addSubview(loginButton) } func setInputUIToolbar() -> UIToolbar { let tool = UIToolbar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 40)) let loginIn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 40)) loginIn.setTitle("登录", for: UIControlState()) loginIn.setTitleColor(UIColor.blue, for: UIControlState()) loginIn.setTitleColor(UIColor.brown, for: UIControlState.highlighted) tool.addSubview(loginIn) let ok = UIButton(frame: CGRect(x: self.view.frame.size.width - 60 , y: 0, width: 60, height: 40)) ok.setTitle("Done", for: UIControlState()) ok.setTitleColor(UIColor.blue, for: UIControlState()) ok.setTitleColor(UIColor.brown, for: UIControlState.highlighted) tool.addSubview(ok) //frame: CGRect(x: self.view.frame.size.width - 60 , y: 0, width: 60, height: 40) return tool } //TextField按返回键的反应 func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } //跳到注册页 func register(){ let register = UserRegisterViewController() self.navigationController?.pushViewController(register, animated: true) } //关闭 func close(_ button: UIButton){ self.dismiss(animated: true) { () -> Void in //print("close") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
edebe48e44c626ec6802699fe6418db9
37.013423
156
0.621116
4.623673
false
false
false
false
ReactiveKit/ReactiveUIKit
Sources/UIBarButtonItem.swift
1
1283
// // UIBarButtonItem.swift // ReactiveUIKit // // Created by Srdan Rasic on 02/04/16. // Copyright © 2016 Srdan Rasic. All rights reserved. // import UIKit import ReactiveKit @objc class RKUIBarButtonItemHelper: NSObject { weak var barButtonItem: UIBarButtonItem? let pushStream = PushStream<Void>() init(barButtonItem: UIBarButtonItem) { self.barButtonItem = barButtonItem super.init() barButtonItem.target = self barButtonItem.action = #selector(RKUIBarButtonItemHelper.barButtonItemDidTap) } func barButtonItemDidTap() { pushStream.next() } deinit { barButtonItem?.target = nil pushStream.completed() } } extension UIBarButtonItem { private struct AssociatedKeys { static var BarButtonItemHelperKey = "r_BarButtonItemHelperKey" } public var rTap: Stream<Void> { if let helper: AnyObject = objc_getAssociatedObject(self, &AssociatedKeys.BarButtonItemHelperKey) { return (helper as! RKUIBarButtonItemHelper).pushStream.toStream() } else { let helper = RKUIBarButtonItemHelper(barButtonItem: self) objc_setAssociatedObject(self, &AssociatedKeys.BarButtonItemHelperKey, helper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return helper.pushStream.toStream() } } }
mit
115f48ee144c2b867eb2af734ea9104c
25.163265
142
0.73791
4.466899
false
false
false
false
cdmx/MiniMancera
miniMancera/View/OptionWhistlesVsZombies/Board/VOptionWhistlesVsZombiesBoardCellScore.swift
1
3241
import UIKit class VOptionWhistlesVsZombiesBoardCellScore:UICollectionViewCell { private weak var imageView:UIImageView! private weak var labelTitle:UILabel! private let kImageWidth:CGFloat = 90 private let kImageRight:CGFloat = -30 override init(frame:CGRect) { super.init(frame:frame) clipsToBounds = true backgroundColor = UIColor.clear isUserInteractionEnabled = false let imageView:UIImageView = UIImageView() imageView.isUserInteractionEnabled = false imageView.clipsToBounds = true imageView.contentMode = UIViewContentMode.center imageView.translatesAutoresizingMaskIntoConstraints = false self.imageView = imageView let labelTitle:UILabel = UILabel() labelTitle.isUserInteractionEnabled = false labelTitle.translatesAutoresizingMaskIntoConstraints = false labelTitle.backgroundColor = UIColor.clear labelTitle.font = UIFont.regular(size:11) labelTitle.textColor = UIColor.white labelTitle.textAlignment = NSTextAlignment.right self.labelTitle = labelTitle addSubview(imageView) addSubview(labelTitle) NSLayoutConstraint.equalsVertical( view:imageView, toView:self) NSLayoutConstraint.rightToRight( view:imageView, toView:self, constant:kImageRight) NSLayoutConstraint.width( view:imageView, constant:kImageWidth) NSLayoutConstraint.equalsVertical( view:labelTitle, toView:self) NSLayoutConstraint.leftToLeft( view:labelTitle, toView:self) NSLayoutConstraint.rightToLeft( view:labelTitle, toView:imageView) } required init?(coder:NSCoder) { return nil } //MARK: private private func imageForAmount(amount:Int) { switch amount { case 0: imageView.image = #imageLiteral(resourceName: "assetWhistlesVsZombiesBoardScore0") break case 1: imageView.image = #imageLiteral(resourceName: "assetWhistlesVsZombiesBoardScore1") break case 2: imageView.image = #imageLiteral(resourceName: "assetWhistlesVsZombiesBoardScore2") break case 3: imageView.image = #imageLiteral(resourceName: "assetWhistlesVsZombiesBoardScore3") break case 4: imageView.image = #imageLiteral(resourceName: "assetWhistlesVsZombiesBoardScore4") break default: imageView.image = #imageLiteral(resourceName: "assetWhistlesVsZombiesBoardScore5") break } } //MARK: public func config(model:MOptionWhistlesVsZombiesBoardScoreItem) { imageForAmount(amount:model.amount) labelTitle.text = model.title } }
mit
8b93999d90c88a564e20741d64c16e00
27.429825
94
0.587782
6.281008
false
false
false
false
DrabWeb/Komikan
Komikan/Komikan/KMReaderScrollView.swift
1
5287
// // KMReaderScrollView.swift // Komikan // // Created by Seth on 2016-02-20. // import Cocoa class KMReaderScrollView: NSScrollView { // Make it so we can always receive mouse events override var acceptsFirstResponder : Bool { return true } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) // Drawing code here. } /// The monitor for the local magnify event var magnifyMonitor : AnyObject?; required init?(coder: NSCoder) { super.init(coder: coder); // Subscribe to the magnify event magnifyMonitor = NSEvent.addLocalMonitorForEvents(matching: NSEventMask.magnify, handler: magnifyEvent) as AnyObject?; } func magnifyEvent(_ event: NSEvent) -> NSEvent { // Add the magnification amount to the current magnification amount self.magnification = event.magnification + self.magnification; // Return the event return event; } /// Destroys all the NSEvent monitors for this window func removeAllMonitors() { // Remove the monitors NSEvent.removeMonitor(magnifyMonitor!); } /// The reader view controller we want to flip pages for var readerViewController : KMReaderViewController! /// Flips to the next page func nextPage() { // Go to the next page readerViewController.nextPage(); } /// Flips to the previous page func previousPage() { // Go to the previous page readerViewController.previousPage(); } /// The swipe cooldown so you cant swipe until the delta X is at 0 var swipeCooldownOver : Bool = true; /// For some reason the trackpad when swiping would flip pages twice. This number is used so only every two swipes it will flip pages var pageSwipeCount : Int = 0; // This is called not only when you scroll, but when you swipe the trackpad. This should also work with Magic Mouse(Not tested) override func scrollWheel(with theEvent: NSEvent) { /// Did we flip the page? var flippedPages : Bool = false; // If the delta X is less than 5(Meaning you are swiping left)... if(theEvent.deltaX < -5) { // If the swipe cooldown is over... if(swipeCooldownOver) { // Add 1 to the page swipe count pageSwipeCount += 1; // If the page swipe count is 2... if(pageSwipeCount == 2) { // If the horizontal scroll amout is 1... if(self.horizontalScroller?.floatValue == 1) { // Go to the next page nextPage(); // Say we flipped pages flippedPages = true; } // If the scroll view is just not magnified... else if(self.magnification == 1) { // Go to the next page nextPage(); // Say we flipped pages flippedPages = true; } // Set the page swipe count to 0 pageSwipeCount = 0; } } // Say the cooldown isnt over swipeCooldownOver = false; } // If the delta X is greater than 5(Meaning you are swiping right)... else if(theEvent.deltaX > 5) { // If the swipe cooldown is over... if(swipeCooldownOver) { // Add 1 to the page swipe count pageSwipeCount += 1; // If the page swipe count is 2... if(pageSwipeCount == 2) { // If the horizontal scroll amout is 0... if(self.horizontalScroller?.floatValue == 0) { // Go to the previous page previousPage(); // Say we flipped pages flippedPages = true; } // If the scroll view is just not magnified... else if(self.magnification == 1) { // Go to the previous page previousPage(); // Say we flipped pages flippedPages = true; } // Set the page swipe count to 0 pageSwipeCount = 0; } } // Say the swipe cooldown isnt over swipeCooldownOver = false; } // If the trackpad's scroll force on the X is 0... else if(theEvent.deltaX == 0) { // Say the cooldown is over swipeCooldownOver = true; } // If we didnt flip pages and we are zoomed in... if(!flippedPages && self.magnification > 1) { // Tell the scroll view to scroll super.scrollWheel(with: theEvent); } } }
gpl-3.0
bbd6a93c5ad2ef5b0094d94886512533
33.555556
137
0.497636
5.40593
false
false
false
false
edx/edx-app-ios
Source/HTMLBlockViewController.swift
1
12854
// // HTMLBlockViewController.swift // edX // // Created by Akiva Leffert on 5/26/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit class HTMLBlockViewController: UIViewController, CourseBlockViewController, PreloadableBlockController { public typealias Environment = OEXAnalyticsProvider & OEXConfigProvider & DataManagerProvider & OEXSessionProvider & ReachabilityProvider & NetworkManagerProvider & OEXRouterProvider & OEXInterfaceProvider public let courseID: String public let blockID: CourseBlockID? var block: CourseBlock? { return courseQuerier.blockWithID(id: blockID).firstSuccess().value } private let environment: Environment private let subkind: CourseHTMLBlockSubkind private lazy var courseDateBannerView = CourseDateBannerView(frame: .zero) private let webController: AuthenticatedWebViewController private let loader = BackedStream<CourseBlock>() private let courseDateBannerLoader = BackedStream<(CourseDateBannerModel)>() private let courseQuerier: CourseOutlineQuerier private lazy var openInBrowserView = OpenInExternalBrowserView(frame: .zero) public init(blockID: CourseBlockID?, courseID: String, environment: Environment, subkind: CourseHTMLBlockSubkind) { self.courseID = courseID self.blockID = blockID self.subkind = subkind self.environment = environment webController = AuthenticatedWebViewController(environment: environment, shouldListenForAjaxCallbacks: true) courseQuerier = environment.dataManager.courseDataManager.querierForCourseWithID(courseID: courseID, environment: environment) super.init(nibName : nil, bundle : nil) webController.delegate = self webController.ajaxCallbackDelegate = self addObserver() setupViews() loadWebviewStream() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func addObserver() { NotificationCenter.default.oex_addObserver(observer: self, name: NOTIFICATION_SHIFT_COURSE_DATES) { _, observer, _ in observer.hideCourseBannerView() observer.webController.reload() } } private func setupViews() { view.addSubview(courseDateBannerView) courseDateBannerView.snp.makeConstraints { make in make.trailing.equalTo(view) make.leading.equalTo(view) make.top.equalTo(view) make.height.equalTo(0) } addChild(webController) webController.didMove(toParent: self) view.addSubview(webController.view) configureViews() } private func configureViews(containsiFrame: Bool = false) { if subkind == .Base, !containsiFrame { webController.view.snp.remakeConstraints { make in make.trailing.equalTo(view) make.leading.equalTo(view) make.top.equalTo(courseDateBannerView.snp.bottom) make.bottom.equalTo(view) } } else { if view.subviews.contains(openInBrowserView) { openInBrowserView.removeFromSuperview() openInBrowserView.delegate = nil } view.addSubview(openInBrowserView) openInBrowserView.delegate = self webController.view.snp.remakeConstraints { make in make.trailing.equalTo(view) make.leading.equalTo(view) make.top.equalTo(courseDateBannerView.snp.bottom) } openInBrowserView.snp.remakeConstraints { make in make.leading.equalTo(view) make.trailing.equalTo(view) make.top.equalTo(webController.view.snp.bottom) make.height.equalTo(55) make.bottom.equalTo(safeBottom) } trackOpenInBrowserBannerEvent(displayName: AnalyticsDisplayName.OpenInBrowserBannerDisplayed, eventName: AnalyticsEventName.OpenInBrowserBannerDisplayed) } } private func loadWebviewStream(_ forceLoad: Bool = false) { if !loader.hasBacking || forceLoad { let courseQuerierStream = courseQuerier.blockWithID(id: self.blockID).firstSuccess() loader.addBackingStream(courseQuerierStream) courseQuerierStream.listen((self), success: { [weak self] block in if let url = block.blockURL { let request = NSURLRequest(url: url as URL) self?.webController.loadRequest(request: request) } else { self?.webController.showError(error: nil) } }, failure: { [weak self] error in self?.webController.showError(error: error) }) } } private func loadBannerStream() { guard subkind == .Problem, let isSelfPaced = environment.dataManager.enrollmentManager.enrolledCourseWithID(courseID: courseID)?.course.isSelfPaced, isSelfPaced else { return } let courseBannerRequest = CourseDateBannerAPI.courseDateBannerRequest(courseID: courseID) let courseBannerStream = environment.networkManager.streamForRequest(courseBannerRequest) courseDateBannerLoader.addBackingStream(courseBannerStream) courseBannerStream.listen((self), success: { [weak self] courseBannerModel in self?.loadCourseDateBannerView(bannerModel: courseBannerModel) }, failure: { _ in }) } private func loadCourseDateBannerView(bannerModel: CourseDateBannerModel) { var height: CGFloat = 0 if bannerModel.hasEnded { height = 0 } else { guard let status = bannerModel.bannerInfo.status else { return } if status == .resetDatesBanner { courseDateBannerView.delegate = self courseDateBannerView.bannerInfo = bannerModel.bannerInfo courseDateBannerView.setupView() trackDateBannerAppearanceEvent(bannerModel: bannerModel) height = courseDateBannerView.heightForView(width: view.frame.size.width) } } courseDateBannerView.snp.remakeConstraints { make in make.trailing.equalTo(view) make.leading.equalTo(view) make.top.equalTo(view) make.height.equalTo(height) } UIView.animate(withDuration: 0.1) { [weak self] in self?.view.layoutIfNeeded() } } private func hideCourseBannerView() { courseDateBannerView.snp.remakeConstraints { make in make.trailing.equalTo(view) make.leading.equalTo(view) make.top.equalTo(view) make.height.equalTo(0) } UIView.animate(withDuration: 0.1) { [weak self] in self?.view.layoutIfNeeded() } } public func preloadData() { loadWebviewStream() } private func resetCourseDate() { trackDatesShiftTapped() let request = CourseDateBannerAPI.courseDatesResetRequest(courseID: courseID) environment.networkManager.taskForRequest(request) { [weak self] result in if let _ = result.error { self?.trackDatesShiftEvent(success: false) self?.showDateResetSnackBar(message: Strings.Coursedates.ResetDate.errorMessage) } else { self?.trackDatesShiftEvent(success: true) self?.showSnackBar() self?.postCourseDateResetNotification() } } } private func trackDateBannerAppearanceEvent(bannerModel: CourseDateBannerModel) { guard let eventName = bannerModel.bannerInfo.status?.analyticsEventName, let bannerType = bannerModel.bannerInfo.status?.analyticsBannerType, let courseMode = environment.dataManager.enrollmentManager.enrolledCourseWithID(courseID: courseID)?.mode else { return } environment.analytics.trackDatesBannerAppearence(screenName: AnalyticsScreenName.AssignmentScreen, courseMode: courseMode, eventName: eventName, bannerType: bannerType) } private func trackDatesShiftTapped() { guard let courseMode = environment.dataManager.enrollmentManager.enrolledCourseWithID(courseID: courseID)?.mode else { return } environment.analytics.trackDatesShiftButtonTapped(screenName: AnalyticsScreenName.AssignmentScreen, courseMode: courseMode) } private func trackDatesShiftEvent(success: Bool) { guard let courseMode = environment.dataManager.enrollmentManager.enrolledCourseWithID(courseID: courseID)?.mode else { return } environment.analytics.trackDatesShiftEvent(screenName: AnalyticsScreenName.AssignmentScreen, courseMode: courseMode, success: success) } private func showSnackBar() { showDateResetSnackBar(message: Strings.Coursedates.toastSuccessMessage, buttonText: Strings.Coursedates.viewAllDates, showButton: true) { [weak self] in if let weakSelf = self { weakSelf.environment.router?.showDatesTabController(controller: weakSelf) weakSelf.hideSnackBar() } } } private func trackOpenInBrowserBannerEvent(displayName: AnalyticsDisplayName, eventName: AnalyticsEventName) { let enrollment = environment.interface?.enrollmentForCourse(withID: courseID)?.type ?? .none environment.analytics.trackOpenInBrowserBannerEvent(displayName: displayName, eventName: eventName, userType: enrollment.rawValue, courseID: courseID, componentID: blockID ?? "", componentType: block?.typeName ?? "", openURL: block?.webURL?.absoluteString ?? "") } private func postCourseDateResetNotification() { NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: NOTIFICATION_SHIFT_COURSE_DATES))) } private func markBlockAsComplete() { if let block = block { if !block.isCompleted { block.isCompleted = true } } } deinit { NotificationCenter.default.removeObserver(self) } } extension HTMLBlockViewController: AuthenticatedWebViewControllerDelegate { func authenticatedWebViewController(authenticatedController: AuthenticatedWebViewController, didFinishLoading webview: WKWebView) { authenticatedController.setLoadControllerState(withState: .Loaded) loadBannerStream() elavuateHTMLForiFrame(with: webview) } func elavuateHTMLForiFrame(with webview: WKWebView) { if subkind == .Base { // The type of HTML basic component and one created with iframe tool is same which is HTML // To find out either the HTML block is created with iframe tool or not we need to look into the HTML let javascript = "try { var top_div_list = document.querySelectorAll('div[data-usage-id=\"\(blockID ?? "")\"]'); top_div_list.length == 1 && top_div_list[0].querySelectorAll(\"iframe\").length > 0; } catch { false; };" webview.evaluateJavaScript(javascript) { [weak self] (containsiframe: Any?, error: Error?) in if let containsiframe = containsiframe as? Bool, containsiframe { self?.configureViews(containsiFrame: true) } } } } } extension HTMLBlockViewController: CourseShiftDatesDelegate { func courseShiftDateButtonAction() { resetCourseDate() } } extension HTMLBlockViewController: AJAXCompletionCallbackDelegate { func didCompletionCalled(completion: Bool) { markBlockAsComplete() } } extension HTMLBlockViewController: OpenInExternalBrowserViewDelegate, BrowserViewControllerDelegate { func openInExternalBrower() { guard let blockID = block?.blockID, let parent = courseQuerier.parentOfBlockWith(id: blockID).firstSuccess().value, let unitURL = parent.blockURL as URL? else { return } trackOpenInBrowserBannerEvent(displayName: AnalyticsDisplayName.OpenInBrowserBannerTapped, eventName: AnalyticsEventName.OpenInBrowserBannerTapped) environment.router?.showBrowserViewController(from: self, title: parent.displayName, url: unitURL) } // We want to force reload the component screen because if the learner has taken any action // on the in-app browser screen, the learner get updated experience on the component as well func didDismissBrowser() { loadWebviewStream(true) } }
apache-2.0
a690eb496e255323fcb9e0912694e2a4
40.598706
270
0.663918
5.104845
false
false
false
false
sopinetchat/SopinetChat-iOS
Pod/Factories/SChatToolbarButtonFactory.swift
1
2914
// // SChatToolbarButtonFactory.swift // Pods // // Created by David Moreno Lora on 29/4/16. // // import UIKit import Foundation public class SChatToolbarButtonFactory { // MARK: Functions static func defaultAccessoryButtonItem() -> UIButton { // TODO: Improve this with mask for other states let accessoryImage: UIImage = UIImage.sChatDefaultAccesoryImage() let normalImage = accessoryImage.sChatImageMaskedWithColor(UIColor.lightGrayColor()) let highlightedImage = accessoryImage.sChatImageMaskedWithColor(UIColor.darkGrayColor()) let accessoryButton: UIButton = UIButton(frame: CGRectMake(0.0, 0.0, accessoryImage.size.width, 32.0)) accessoryButton.setImage(normalImage, forState: .Normal) accessoryButton.setImage(highlightedImage, forState: .Highlighted) accessoryButton.contentMode = .ScaleAspectFit accessoryButton.backgroundColor = UIColor.clearColor() accessoryButton.tintColor = UIColor.lightGrayColor() accessoryButton.accessibilityLabel = NSBundle.sChatLocalizedStringForKey("schat_share_media") return accessoryButton } static func defaultSendButtonItem() -> UIButton { let sendTitle: NSString = NSBundle.sChatLocalizedStringForKey("schat_send") let sendButton = UIButton(frame: CGRectZero) sendButton.setTitle(sendTitle as String, forState: .Normal) sendButton.setTitleColor(UIColor(netHex: blueBubbleColor), forState: .Normal) sendButton.setTitleColor(UIColor(netHex: blueBubbleColor), forState: .Highlighted) sendButton.setTitleColor(UIColor.lightGrayColor(), forState: .Disabled) sendButton.tintColor = UIColor(netHex: blueBubbleColor) sendButton.titleLabel?.font = UIFont.boldSystemFontOfSize(17.0) sendButton.titleLabel?.adjustsFontSizeToFitWidth = true; sendButton.titleLabel?.minimumScaleFactor = 0.85; sendButton.contentMode = .Center sendButton.backgroundColor = UIColor.clearColor() let maxHeight: CGFloat = 32.0 let sendTitleRect = sendTitle.boundingRectWithSize(CGSizeMake(CGFloat.max, maxHeight), options: [NSStringDrawingOptions.UsesLineFragmentOrigin, NSStringDrawingOptions.UsesFontLeading], attributes: [NSFontAttributeName : (sendButton.titleLabel?.font)!], context: nil) sendButton.frame = CGRectMake(0.0, 0.0, CGRectGetWidth(CGRectIntegral(sendTitleRect)), maxHeight) return sendButton } }
gpl-3.0
9248cb9125844b141641f4cc30899290
40.042254
171
0.629032
5.839679
false
false
false
false
garricn/secret
FLYR/FlyrFetcher.swift
1
2031
// // PhotoFetcher.swift // FLYR // // Created by Garric Nahapetian on 8/6/16. // Copyright © 2016 Garric Nahapetian. All rights reserved. // import CloudKit import UIKit import Bond typealias CKRecords = [CKRecord] typealias Flyrs = [Flyr] protocol FlyrFetchable { var output: EventProducer<Flyrs> { get } var errorOutput: EventProducer<ErrorType?> { get } func fetch(with query: CKQuery) func fetch(with operation: CKQueryOperation, and query: CKQuery) } struct FlyrFetcher: FlyrFetchable { let output = EventProducer<Flyrs>() let errorOutput = EventProducer<ErrorType?>() private let database: Database init(database: Database) { self.database = database } func fetch(with operation: CKQueryOperation, and query: CKQuery) { database.add(operation) fetch(with: query) } func fetch(with query: CKQuery) { database.perform(query) { response in guard case .Successful(let records as CKRecords) = response else { if case .NotSuccessful(let error) = response { self.errorOutput.next(error) } return } let flyrs = records.map(toFlyr) self.output.next(flyrs) } } } struct Error: ErrorType { let message: String } func toFlyr(record: CKRecord) -> Flyr { return Flyr( image: image(from: record), location: location(from: record), startDate: startDate(from: record), ownerReference: ownerReference(from: record) ) } func image(from record: CKRecord) -> UIImage { let imageAsset = record["image"] as! CKAsset let path = imageAsset.fileURL.path! return UIImage(contentsOfFile: path)! } func location(from record: CKRecord) -> CLLocation { return record["location"] as! CLLocation } func startDate(from record: CKRecord) -> NSDate { return record["startDate"] as! NSDate } func ownerReference(from record: CKRecord) -> CKReference { return record["ownerReference"] as! CKReference }
mit
849f1d23ad426f17039e208f4ead7452
24.3875
93
0.661084
3.996063
false
false
false
false
gzios/swift
SwiftBase/GZWB/GZWB/Classes/Main(主要)/MainViewController.swift
1
1979
// // MainViewController.swift // GZWB // // Created by ATabc on 2017/6/20. // Copyright © 2017年 ATabc. All rights reserved. // import UIKit class MainViewController: UITabBarController { // lazy var composeBtn : UIButton = UIButton.createButton("tabbar_compose_button", bgImageName: "tabbar_compose_button_highlighted") lazy var composeBtn : UIButton = UIButton("tabbar_compose_icon_add", bgImageName: "tabbar_compose_button") override func viewDidLoad() { super.viewDidLoad() setupComposeBtn() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setupTabbarItems() } } //MARK:- 设置UI界面 extension MainViewController{ func setupComposeBtn(){ tabBar.addSubview(composeBtn) composeBtn.center = CGPoint(x:tabBar.center.x,y:tabBar.bounds.size.height * 0.5) //监听按钮的点击 //Selector三种写法Selector("composeBtnClick") "composeBtnClick" #selector(MainViewController.composeBtnClick) composeBtn.addTarget(self, action: #selector(MainViewController.composeBtnClick) , for: .touchUpInside) } //避免外部使用 @objc private func composeBtnClick(){ print(#line) } func setupTabbarItems(){ for i in 0..<tabBar.items!.count { if i == 2 { let item = tabBar.items![i] item.isEnabled = false return } } } } //MARK:- 事件处理 extension MainViewController { //事件监听本质是发送消息,但是发送消息的是OC //将方法包装成@SEL -》类中查找方法列表-》根据@SEL找到imp指针(函数)-》函数调用 //Swift 中将函数声明为private 那么该该函数就不会被添加到方法列表 // func composeBtnClick() { // print(#line) // } //分类中是不允许那样被使用了 }
apache-2.0
88e9b1bc411bafc3979021254763b080
24.362319
135
0.624
3.932584
false
false
false
false
lbkchen/cvicu-app
complicationsapp/Pods/Eureka/Source/Core/Form.swift
1
13190
// Form.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation /// The delegate of the Eureka form. public protocol FormDelegate : class { func sectionsHaveBeenAdded(sections: [Section], atIndexes: NSIndexSet) func sectionsHaveBeenRemoved(sections: [Section], atIndexes: NSIndexSet) func sectionsHaveBeenReplaced(oldSections oldSections:[Section], newSections: [Section], atIndexes: NSIndexSet) func rowsHaveBeenAdded(rows: [BaseRow], atIndexPaths:[NSIndexPath]) func rowsHaveBeenRemoved(rows: [BaseRow], atIndexPaths:[NSIndexPath]) func rowsHaveBeenReplaced(oldRows oldRows:[BaseRow], newRows: [BaseRow], atIndexPaths: [NSIndexPath]) func rowValueHasBeenChanged(row: BaseRow, oldValue: Any?, newValue: Any?) } //MARK: Form /// The class representing the Eureka form. public final class Form { /// Defines the default options of the navigation accessory view. public static var defaultNavigationOptions = RowNavigationOptions.Enabled.union(.SkipCanNotBecomeFirstResponderRow) /// The default options that define when an inline row will be hidden. Applies only when `inlineRowHideOptions` is nil. public static var defaultInlineRowHideOptions = InlineRowHideOptions.FirstResponderChanges.union(.AnotherInlineRowIsShown) /// The options that define when an inline row will be hidden. If nil then `defaultInlineRowHideOptions` are used public var inlineRowHideOptions : InlineRowHideOptions? /// Which `UIReturnKeyType` should be used by default. Applies only when `keyboardReturnType` is nil. public static var defaultKeyboardReturnType = KeyboardReturnTypeConfiguration() /// Which `UIReturnKeyType` should be used in this form. If nil then `defaultKeyboardReturnType` is used public var keyboardReturnType : KeyboardReturnTypeConfiguration? /// This form's delegate public weak var delegate: FormDelegate? public init(){} /** Returns the row at the given indexPath */ public subscript(indexPath: NSIndexPath) -> BaseRow { return self[indexPath.section][indexPath.row] } /** Returns the row whose tag is passed as parameter. Uses a dictionary to get the row faster */ public func rowByTag<T: Equatable>(tag: String) -> RowOf<T>? { let row: BaseRow? = rowByTag(tag) return row as? RowOf<T> } /** Returns the row whose tag is passed as parameter. Uses a dictionary to get the row faster */ public func rowByTag<Row: RowType>(tag: String) -> Row? { let row: BaseRow? = rowByTag(tag) return row as? Row } /** Returns the row whose tag is passed as parameter. Uses a dictionary to get the row faster */ public func rowByTag(tag: String) -> BaseRow? { return rowsByTag[tag] } /** Returns the section whose tag is passed as parameter. */ public func sectionByTag(tag: String) -> Section? { return kvoWrapper._allSections.filter( { $0.tag == tag }).first } /** Method used to get all the values of all the rows of the form. Only rows with tag are included. - parameter includeHidden: If the values of hidden rows should be included. - returns: A dictionary mapping the rows tag to its value. [tag: value] */ public func values(includeHidden includeHidden: Bool = false) -> [String: Any?]{ if includeHidden { return allRows.filter({ $0.tag != nil }) .reduce([String: Any?]()) { var result = $0 result[$1.tag!] = $1.baseValue return result } } return rows.filter({ $0.tag != nil }) .reduce([String: Any?]()) { var result = $0 result[$1.tag!] = $1.baseValue return result } } /** Set values to the rows of this form - parameter values: A dictionary mapping tag to value of the rows to be set. [tag: value] */ public func setValues(values: [String: Any?]){ for (key, value) in values{ let row: BaseRow? = rowByTag(key) row?.baseValue = value } } /// The visible rows of this form public var rows: [BaseRow] { return flatMap { $0 } } /// All the rows of this form. Includes the hidden rows. public var allRows: [BaseRow] { return kvoWrapper._allSections.map({ $0.kvoWrapper._allRows }).flatMap { $0 } } /** * Hides all the inline rows of this form. */ public func hideInlineRows() { for row in self.allRows { if let inlineRow = row as? BaseInlineRowType { inlineRow.collapseInlineRow() } } } //MARK: Private var rowObservers = [String: [ConditionType: [Taggable]]]() var rowsByTag = [String: BaseRow]() var tagToValues = [String: AnyObject]() private lazy var kvoWrapper : KVOWrapper = { [unowned self] in return KVOWrapper(form: self) }() } extension Form : MutableCollectionType { // MARK: MutableCollectionType public var startIndex: Int { return 0 } public var endIndex: Int { return kvoWrapper.sections.count } public subscript (position: Int) -> Section { get { return kvoWrapper.sections[position] as! Section } set { kvoWrapper.sections[position] = newValue } } } extension Form : RangeReplaceableCollectionType { // MARK: RangeReplaceableCollectionType public func append(formSection: Section){ kvoWrapper.sections.insertObject(formSection, atIndex: kvoWrapper.sections.count) kvoWrapper._allSections.append(formSection) formSection.wasAddedToForm(self) } public func appendContentsOf<S : SequenceType where S.Generator.Element == Section>(newElements: S) { kvoWrapper.sections.addObjectsFromArray(newElements.map { $0 }) kvoWrapper._allSections.appendContentsOf(newElements) for section in newElements{ section.wasAddedToForm(self) } } public func reserveCapacity(n: Int){} public func replaceRange<C : CollectionType where C.Generator.Element == Section>(subRange: Range<Int>, with newElements: C) { for i in subRange { if let section = kvoWrapper.sections.objectAtIndex(i) as? Section { section.willBeRemovedFromForm() kvoWrapper._allSections.removeAtIndex(kvoWrapper._allSections.indexOf(section)!) } } kvoWrapper.sections.replaceObjectsInRange(NSMakeRange(subRange.startIndex, subRange.endIndex - subRange.startIndex), withObjectsFromArray: newElements.map { $0 }) kvoWrapper._allSections.insertContentsOf(newElements, at: indexForInsertionAtIndex(subRange.startIndex)) for section in newElements{ section.wasAddedToForm(self) } } public func removeAll(keepCapacity keepCapacity: Bool = false) { // not doing anything with capacity for section in kvoWrapper._allSections{ section.willBeRemovedFromForm() } kvoWrapper.sections.removeAllObjects() kvoWrapper._allSections.removeAll() } private func indexForInsertionAtIndex(index: Int) -> Int { guard index != 0 else { return 0 } let row = kvoWrapper.sections[index-1] if let i = kvoWrapper._allSections.indexOf(row as! Section){ return i + 1 } return kvoWrapper._allSections.count } } extension Form { // MARK: Private Helpers class KVOWrapper : NSObject { dynamic var _sections = NSMutableArray() var sections : NSMutableArray { return mutableArrayValueForKey("_sections") } var _allSections = [Section]() weak var form: Form? init(form: Form){ self.form = form super.init() addObserver(self, forKeyPath: "_sections", options: NSKeyValueObservingOptions.New.union(.Old), context:nil) } deinit { removeObserver(self, forKeyPath: "_sections") } override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { let newSections = change?[NSKeyValueChangeNewKey] as? [Section] ?? [] let oldSections = change?[NSKeyValueChangeOldKey] as? [Section] ?? [] guard let delegateValue = form?.delegate, let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKindKey] else { return } guard keyPathValue == "_sections" else { return } switch changeType.unsignedLongValue { case NSKeyValueChange.Setting.rawValue: let indexSet = change![NSKeyValueChangeIndexesKey] as? NSIndexSet ?? NSIndexSet(index: 0) delegateValue.sectionsHaveBeenAdded(newSections, atIndexes: indexSet) case NSKeyValueChange.Insertion.rawValue: let indexSet = change![NSKeyValueChangeIndexesKey] as! NSIndexSet delegateValue.sectionsHaveBeenAdded(newSections, atIndexes: indexSet) case NSKeyValueChange.Removal.rawValue: let indexSet = change![NSKeyValueChangeIndexesKey] as! NSIndexSet delegateValue.sectionsHaveBeenRemoved(oldSections, atIndexes: indexSet) case NSKeyValueChange.Replacement.rawValue: let indexSet = change![NSKeyValueChangeIndexesKey] as! NSIndexSet delegateValue.sectionsHaveBeenReplaced(oldSections: oldSections, newSections: newSections, atIndexes: indexSet) default: assertionFailure() } } } func dictionaryValuesToEvaluatePredicate() -> [String: AnyObject] { return tagToValues } func addRowObservers(taggable: Taggable, rowTags: [String], type: ConditionType) { for rowTag in rowTags{ if rowObservers[rowTag] == nil { rowObservers[rowTag] = Dictionary() } if let _ = rowObservers[rowTag]?[type]{ if !rowObservers[rowTag]![type]!.contains({ $0 === taggable }){ rowObservers[rowTag]?[type]!.append(taggable) } } else{ rowObservers[rowTag]?[type] = [taggable] } } } func removeRowObservers(taggable: Taggable, rows: [String], type: ConditionType) { for row in rows{ guard var arr = rowObservers[row]?[type], let index = arr.indexOf({ $0 === taggable }) else { continue } arr.removeAtIndex(index) } } func nextRowForRow(currentRow: BaseRow) -> BaseRow? { let allRows = rows guard let index = allRows.indexOf(currentRow) else { return nil } guard index < allRows.count - 1 else { return nil } return allRows[index + 1] } func previousRowForRow(currentRow: BaseRow) -> BaseRow? { let allRows = rows guard let index = allRows.indexOf(currentRow) else { return nil } guard index > 0 else { return nil } return allRows[index - 1] } func hideSection(section: Section){ kvoWrapper.sections.removeObject(section) } func showSection(section: Section){ guard !kvoWrapper.sections.containsObject(section) else { return } guard var index = kvoWrapper._allSections.indexOf(section) else { return } var formIndex = NSNotFound while (formIndex == NSNotFound && index > 0){ index = index - 1 let previous = kvoWrapper._allSections[index] formIndex = kvoWrapper.sections.indexOfObject(previous) } kvoWrapper.sections.insertObject(section, atIndex: formIndex == NSNotFound ? 0 : formIndex + 1 ) } }
mit
0f39d1823f253ef65f1d50c1430c91fa
38.972727
170
0.644958
5
false
false
false
false
h-n-y/UICollectionView-TheCompleteGuide
chapter-2/2-selection-view-xib/chapter2-5/ViewController.swift
1
2670
// // ViewController.swift // chapter2-5 // // Created by Hans Yelek on 4/25/16. // Copyright © 2016 Hans Yelek. All rights reserved. // import UIKit class ViewController: UICollectionViewController { // MARK: Instance Members private let imageArray: Array<UIImage> private let colorArray: Array<UIColor> override init(collectionViewLayout layout: UICollectionViewLayout) { imageArray = ViewController.imagesArray() colorArray = ViewController.colorsArray() super.init(collectionViewLayout: layout) } required init?(coder aDecoder: NSCoder) { imageArray = ViewController.imagesArray() colorArray = ViewController.colorsArray() super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() self.collectionView?.allowsMultipleSelection = true } // MARK: Class Members private static let CellReuseIdentifier = "Cell" private class func imagesArray() -> Array<UIImage> { var imageArray = Array<UIImage>() for i in 0..<12 { let imageName = "\(i).jpg" guard let image = UIImage(named: imageName) else { continue } imageArray.append(image) } return imageArray } private class func colorsArray() -> Array<UIColor> { var colorArray = Array<UIColor>() for _ in 0..<10 { colorArray.append(ViewController.randomColor()) } return colorArray } private class func randomColor() -> UIColor { let red = Float(arc4random() % 255) / 255.0 let green = Float(arc4random() % 255) / 255.0 let blue = Float(arc4random() % 255) / 255.0 return UIColor(colorLiteralRed: red, green: green, blue: blue, alpha: 1.0) } } // MARK: - UICollectionViewDataSource extension ViewController { override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return colorArray.count } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imageArray.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ViewController.CellReuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell cell.image = imageArray[indexPath.item] cell.backgroundColor = colorArray[indexPath.section] return cell } }
mit
f40118e43578669fb25eac758af479f5
29.678161
156
0.65118
5.253937
false
false
false
false
benlangmuir/swift
test/stmt/yield.swift
8
2438
// RUN: %target-typecheck-verify-swift struct YieldRValue { var property: String { _read { yield "hello" } } } struct YieldVariables { var property: String { _read { yield "" } _modify { var x = "" yield &x } } var wrongTypes: String { _read { yield 0 // expected-error {{cannot convert value of type 'Int' to expected yield type 'String'}} } _modify { var x = 0 yield &x // expected-error {{cannot yield reference to storage of type 'Int' as an inout yield of type 'String'}} } } var rvalue: String { get {} _modify { yield &"" // expected-error {{cannot yield immutable value of type 'String' as an inout yield}} } } var missingAmp: String { get {} _modify { var x = "" yield x // expected-error {{yielding mutable value of type 'String' requires explicit '&'}} } } } protocol HasProperty { associatedtype Value var property: Value { get set } } struct GenericTypeWithYields<T> : HasProperty { var storedProperty: T? var property: T { _read { yield storedProperty! } _modify { yield &storedProperty! } } subscript<U>(u: U) -> (T,U) { _read { yield ((storedProperty!, u)) } _modify { var temp = (storedProperty!, u) yield &temp } } } // 'yield' is a context-sensitive keyword. func yield(_: Int) {} func call_yield() { yield(0) } struct YieldInDefer { var property: String { _read { defer { // expected-warning {{'defer' statement at end of scope always executes immediately}}{{7-12=do}} // FIXME: this recovery is terrible yield "" // expected-error@-1 {{function is unused}} // expected-error@-2 {{consecutive statements on a line must be separated by ';'}} // expected-warning@-3 {{string literal is unused}} } } } } // SR-15066 struct InvalidYieldParsing { var property: String { _read { yield(x: "test") // expected-error {{unexpected label in 'yield' statement}} {{13-16=}} yield(x: "test", y: {0}) // expected-error {{expected 1 yield value(s)}} // expected-error@-1 {{unexpected label in 'yield' statement}} {{13-16=}} // expected-error@-2 {{unexpected label in 'yield' statement}} {{24-29=}} yield(_: "test") // expected-error {{unexpected label in 'yield' statement}} {{13-16=}} } } }
apache-2.0
d4c417b883ba59d9c0ee40d34645f3f1
21.785047
119
0.581214
3.791602
false
false
false
false
qinting513/SwiftNote
youtube/YouTube/ViewControllers/MainViewController.swift
1
6346
// // MainViewController.swift // YouTube // // Created by Haik Aslanyan on 7/6/16. // Copyright © 2016 Haik Aslanyan. All rights reserved. // import UIKit class MainViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout, SettingsDelegate, SearchDelegate, TabBarDelegate { //MARK: Properties var views = [UIView]() let items = ["Home", "Trending", "Subscriptions", "Account"] var viewsAreInitialized = false // collectionView 的懒加载 lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 let cv: UICollectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: (self.view.bounds.height)), collectionViewLayout: layout) cv.delegate = self cv.dataSource = self cv.showsHorizontalScrollIndicator = false cv.backgroundColor = UIColor.clear cv.bounces = false cv.isPagingEnabled = true cv.isDirectionalLockEnabled = true return cv }() lazy var tabBar: TabBar = { let tb = TabBar.init(frame: CGRect.init(x: 0, y: 0, width: globalVariables.width, height: 64)) tb.delegate = self return tb }() lazy var settings: Settings = { let st = Settings.init(frame: UIScreen.main.bounds) st.delegate = self return st }() lazy var search: Search = { let se = Search.init(frame: UIScreen.main.bounds) se.delegate = self return se }() let titleLabel: UILabel = { let tl = UILabel.init(frame: CGRect.init(x: 20, y: 5, width: 200, height: 30)) tl.font = UIFont.systemFont(ofSize: 18) tl.textColor = UIColor.white tl.text = "Home" return tl }() //MARK: Methods func customization() { //CollectionView Customization self.collectionView.contentInset = UIEdgeInsetsMake(44, 0, 0, 0) self.view.addSubview(self.collectionView) //NavigationController Customization self.navigationController?.view.backgroundColor = UIColor.rbg(r: 228, g: 34, b: 24) self.navigationController?.navigationItem.hidesBackButton = true self.navigationItem.hidesBackButton = true //NavigationBar color and shadow self.navigationController?.navigationBar.barTintColor = UIColor.rbg(r: 228, g: 34, b: 24) self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) self.navigationController?.navigationBar.shadowImage = UIImage() // TitleLabel self.navigationController?.navigationBar.addSubview(self.titleLabel) //TabBar self.view.addSubview(self.tabBar) //ViewControllers init for title in self.items { let storyBoard = self.storyboard! let vc = storyBoard.instantiateViewController(withIdentifier: title) self.addChildViewController(vc) vc.view.frame = CGRect.init(x: 0, y: 0, width: self.view.bounds.width, height: (self.view.bounds.height - 44)) vc.didMove(toParentViewController: self) self.views.append(vc.view) } self.viewsAreInitialized = true } //MARK: Search and Settings @IBAction func handleSearch(_ sender: AnyObject) { if let window = UIApplication.shared.keyWindow { window.addSubview(self.search) self.search.animate() } } @IBAction func handleMore(_ sender: AnyObject) { if let window = UIApplication.shared.keyWindow { window.addSubview(self.settings) self.settings.animate() } } func hideBar(notification: NSNotification) { let state = notification.object as! Bool self.navigationController?.setNavigationBarHidden(state, animated: true) } //MARK: Delegates implementation func didSelectItem(atIndex: Int) { self.collectionView.scrollRectToVisible(CGRect.init(origin: CGPoint.init(x: (self.view.bounds.width * CGFloat(atIndex)), y: 0), size: self.view.bounds.size), animated: true) } func hideSettingsView(status: Bool) { if status == true { self.settings.removeFromSuperview() } } func hideSearchView(status : Bool){ if status == true { self.search.removeFromSuperview() } } //MARK: VieController lifecyle override func viewDidLoad() { self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell") super.viewDidLoad() customization() didSelectItem(atIndex: 3) NotificationCenter.default.addObserver(self, selector: #selector(MainViewController.hideBar(notification:)), name: NSNotification.Name("hide"), object: nil) } //MARK: CollectionView DataSources func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.views.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) cell.contentView.addSubview(self.views[indexPath.row]) return cell } //MARK: CollectionView Delegates func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize.init(width: self.view.bounds.width, height: (self.view.bounds.height + 22)) } func scrollViewDidScroll(_ scrollView: UIScrollView) { let scrollIndex = Int(round(scrollView.contentOffset.x / self.view.bounds.width)) self.titleLabel.text = self.items[scrollIndex] if self.viewsAreInitialized { self.tabBar.whiteView.frame.origin.x = (scrollView.contentOffset.x / 4) self.tabBar.highlightItem(atIndex: scrollIndex) } } }
apache-2.0
2cecda78afc2fe961b392ed57c889636
36.720238
188
0.652833
4.870869
false
false
false
false
honishi/Hakumai
Hakumai/Global.swift
1
1457
// // Global.swift // Hakumai // // Created by Hiroyuki Onishi on 12/22/14. // Copyright (c) 2014 Hiroyuki Onishi. All rights reserved. // import Foundation import XCGLogger // global logger let log = XCGLogger.default // MARK: Constant value for storyboard contents let kNibNameRoomPositionTableCellView = "RoomPositionTableCellView" let kNibNameTimeTableCellView = "TimeTableCellView" let kNibNameIconTableCellView = "IconTableCellView" let kNibNameUserIdTableCellView = "UserIdTableCellView" let kNibNameCommentTableCellView = "CommentTableCellView" let kNibNamePremiumTableCellView = "PremiumTableCellView" let kRoomPositionColumnIdentifier = "RoomPositionColumn" let kTimeColumnIdentifier = "TimeColumn" let kIconColumnIdentifier = "IconColumn" let kCommentColumnIdentifier = "CommentColumn" let kUserIdColumnIdentifier = "UserIdColumn" let kPremiumColumnIdentifier = "PremiumColumn" // MARK: Common regular expressions // mail address regular expression based on http://qiita.com/sakuro/items/1eaa307609ceaaf51123 let kRegexpMailAddress = "[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*" // MARK: font size let kDefaultFontSize: Float = 13 let kMinimumFontSize: Float = 9 let kMaximumFontSize: Float = 30 // MARK: Common constants let commonUserAgentKey = "User-Agent" let commonUserAgentValue = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"
mit
64311ca462b3b93efb37b1983ddc511e
34.536585
149
0.776253
3.726343
false
false
false
false
yuyedaidao/YQNavigationMenuController
Classes/YQNavigationMenuTitleView.swift
1
1654
// // YQNavigationMenuTitleView.swift // YQNavigationMenuController // // Created by 王叶庆 on 2017/1/12. // Copyright © 2017年 王叶庆. All rights reserved. // import UIKit class YQNavigationMenuTitleView: UIView { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ var scrollView: UIScrollView var titles:[String] = [] { didSet { self.layoutTitleLabels() } } var font: UIFont var normalColor: UIColor var selectedColor: UIColor init(font: UIFont, normalColor: UIColor, selectedColor: UIColor) { self.font = font self.normalColor = normalColor self.selectedColor = selectedColor self.scrollView = UIScrollView() super.init(frame: CGRect.zero) self.prepareViews() } func prepareViews() { self.addSubview(self.scrollView) self.scrollView.fillSuperView() } // override init(frame: CGRect) { // self.scrollView = UIScrollView() // super.init(frame: frame) // self.addSubview(scrollView) // } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func layoutTitleLabels() { for (index, title) in titles.enumerated() { let label = YQNavigationMenuTitleLabel(font: font, normalColor: normalColor, selectedColor: selectedColor, text: title) print(label.textSize()) } } }
mit
2f9662c805a81480cd44e546e1489739
25.435484
131
0.61806
4.490411
false
false
false
false
huajiahen/ChineseSubdivisionsPicker
ChineseSubdivisionsPicker/ChineseSubdivisionsPicker.swift
1
7189
// // ChineseSubdivisionsPicker.swift // ChineseSubdivisionsPickerExample // // Created by huajiahen on 12/7/15. // Copyright © 2015 huajiahen. All rights reserved. // import UIKit public protocol ChineseSubdivisionsPickerDelegate { func subdivisionsPickerDidUpdate(sender: ChineseSubdivisionsPicker) } public class ChineseSubdivisionsPicker: UIPickerView, UIPickerViewDataSource, UIPickerViewDelegate { struct Province { let name: String let cities: [City] } struct City { let name: String let districts: [String] } public enum ChineseSubdivisionsPickerType { case Province case City case District } public var pickerType: ChineseSubdivisionsPickerType = .District { didSet { province = nil city = nil district = nil reloadAllComponents() selectRow(0, inComponent: 0, animated: false) } } public var pickerDelegate: ChineseSubdivisionsPickerDelegate? public var province: String? { get { return __province } set { if let newValue = newValue, index = provinces.indexOf(newValue) where selectedRowInComponent(0) != index { selectRow(index, inComponent: 0, animated: false) } } } public var city: String? { get { return __city } set { if pickerType != .Province, let newValue = newValue, index = cities.indexOf(newValue) where selectedRowInComponent(1) != index { selectRow(index, inComponent: 1, animated: false) } } } public var district: String? { get { return __district } set { if pickerType == .District, let newValue = newValue, index = districts.indexOf(newValue) where selectedRowInComponent(2) != index { selectRow(index, inComponent: 2, animated: false) } } } private lazy var subdivisionsData: [Province] = { let podBundle = NSBundle(forClass: self.classForCoder) guard let path = podBundle.pathForResource("ChineseSubdivisions", ofType: "plist"), localData = NSArray(contentsOfFile: path) as? [[String: [[String: [String]]]]] else { #if DEBUG assertionFailure("ChineseSubdivisionsPicker load data failed.") #endif return [] } return localData.map { provinceData in Province(name: provinceData.keys.first!, cities: provinceData.values.first!.map({ citiesData in City(name: citiesData.keys.first!, districts: citiesData.values.first!) })) } }() private lazy var provinces: [String] = self.subdivisionsData.map({ $0.name }) private var cities: [String] = [] private var districts: [String] = [] private var __province: String? private var __city: String? private var __district: String? override public weak var delegate: UIPickerViewDelegate? { didSet { if delegate !== self { delegate = self } } } override public weak var dataSource: UIPickerViewDataSource? { didSet { if dataSource !== self { dataSource = self } } } //MARK: view life cycle override public func didMoveToWindow() { super.didMoveToWindow() if __province == nil { selectRow(0, inComponent: 0, animated: false) } pickerDelegate?.subdivisionsPickerDidUpdate(self) } //MARK: init override public init(frame: CGRect) { super.init(frame: frame) setupPicker() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupPicker() } func setupPicker() { delegate = self dataSource = self } //MARK: - Picker view data source public func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { switch pickerType { case .Province: return 1 case .City: return 2 case .District: return 3 } } public func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { switch component { case 0: return provinces.count case 1: return cities.count case 2: return districts.count default: return 0 } } //MARK: - Picker view delegate public func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { switch component { case 0: return provinces[row] case 1: guard row != -1 && row < cities.count else { return nil } return cities[row] case 2: guard row != -1 && row < districts.count else { return nil } return districts[row] default: return nil } } public func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch component { case 0: guard __province != provinces[row] else { return } __province = provinces[row] if pickerType != .Province { let citiesInProvince = subdivisionsData[row].cities cities = citiesInProvince.map({ $0.name }) reloadComponent(1) selectRow(0, inComponent: 1, animated: false) } else { pickerDelegate?.subdivisionsPickerDidUpdate(self) } case 1: guard __city != cities[row] else { return } __city = cities[row] if pickerType != .City { guard let province = subdivisionsData.filter({ $0.name == __province }).first, city = province.cities.filter({ $0.name == __city }).first else { return } districts = city.districts reloadComponent(2) selectRow(0, inComponent: 2, animated: false) } else { pickerDelegate?.subdivisionsPickerDidUpdate(self) } case 2: __district = districts[row] pickerDelegate?.subdivisionsPickerDidUpdate(self) default: break } } //MARK: - Other override public func selectRow(row: Int, inComponent component: Int, animated: Bool) { super.selectRow(row, inComponent: component, animated: animated) self.pickerView(self, didSelectRow: row, inComponent: component) } }
mit
062280aa0de739f0acab14a748cdc7e5
28.459016
116
0.537841
5.171223
false
false
false
false
ihugang/json-swift
src/JSValue.Parsing.swift
3
29537
// // JSValue.Parsing.swift // JSON // // Created by David Owens II on 8/12/14. // Copyright (c) 2014 David Owens II. All rights reserved. // import Foundation extension JSValue { /// The type that represents the result of the parse. public typealias JSParsingResult = (value: JSValue?, error: Error?) public typealias JSParsingSequence = UnsafeBufferPointer<UInt8> public static func parse(string: String) -> JSParsingResult { let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! return parse(data) } public static func parse(data: NSData) -> JSParsingResult { let ptr = UnsafePointer<UInt8>(data.bytes) let bytes = UnsafeBufferPointer<UInt8>(start: ptr, count: data.length) return parse(bytes) } /// Parses the given sequence of UTF8 code points and attempts to return a `JSValue` from it. /// /// - parameter seq: The sequence of UTF8 code points. /// /// - returns: A `JSParsingResult` containing the parsed `JSValue` or error information. public static func parse(seq: JSParsingSequence) -> JSParsingResult { let generator = ReplayableGenerator(seq) let result = parse(generator) if let value = result.value { for codeunit in generator { if codeunit.isWhitespace() { continue } else { let remainingText = substring(generator) let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Invalid characters after the last item in the JSON: \(remainingText)"] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } } return (value, nil) } return result } static func parse<S: SequenceType where S.Generator.Element == UInt8>(generator: ReplayableGenerator<S>) -> JSParsingResult { for codeunit in generator { if codeunit.isWhitespace() { continue } if codeunit == Token.LeftCurly { return JSValue.parseObject(generator) } else if codeunit == Token.LeftBracket { return JSValue.parseArray(generator) } else if codeunit.isDigit() || codeunit == Token.Minus { return JSValue.parseNumber(generator) } else if codeunit == Token.t { return JSValue.parseTrue(generator) } else if codeunit == Token.f { return JSValue.parseFalse(generator) } else if codeunit == Token.n { return JSValue.parseNull(generator) } else if codeunit == Token.DoubleQuote || codeunit == Token.SingleQuote { return JSValue.parseString(generator, quote: codeunit) } } let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "No valid JSON value was found to parse in string."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } enum ObjectParsingState { case Initial case Key case Value } static func parseObject<S: SequenceType where S.Generator.Element == UInt8>(generator: ReplayableGenerator<S>) -> JSParsingResult { var state = ObjectParsingState.Initial var key = "" var object = JSObjectType() for (idx, codeunit) in generator.enumerate() { switch (idx, codeunit) { case (0, Token.LeftCurly): continue case (_, Token.RightCurly): switch state { case .Initial: fallthrough case .Value: generator.next() // eat the '}' return (JSValue(object), nil) default: let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Expected token '}' at index: \(idx). Token: \(codeunit). Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } case (_, Token.SingleQuote): fallthrough case (_, Token.DoubleQuote): switch state { case .Initial: state = .Key let parsedKey = parseString(generator, quote: codeunit) if let parsedKey = parsedKey.value?.string { key = parsedKey generator.replay() } else { return (nil, parsedKey.error) } default: let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Expected token ''' (single quote) or '\"' at index: \(idx). Token: \(codeunit). Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } case (_, Token.Colon): switch state { case .Key: state = .Value let parsedValue = parse(generator) if let value = parsedValue.value { object[key] = value generator.replay() } else { return (nil, parsedValue.error) } default: let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Expected token ':' at index: \(idx). Token: \(codeunit). Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } case (_, Token.Comma): switch state { case .Value: state = .Initial key = "" default: let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Expected token ',' at index: \(idx). Token: \(codeunit). Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } default: if codeunit.isWhitespace() { continue } else { let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Unexpected token at index: \(idx). Token: \(codeunit). Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } } } let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Unable to parse object. Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } static func parseArray<S: SequenceType where S.Generator.Element == UInt8>(generator: ReplayableGenerator<S>) -> JSParsingResult { var values = [JSValue]() for (idx, codeunit) in generator.enumerate() { switch (idx, codeunit) { case (0, Token.LeftBracket): continue case (_, Token.RightBracket): generator.next() // eat the ']' return (JSValue(JSBackingValue.JSArray(values)), nil) default: if codeunit.isWhitespace() || codeunit == Token.Comma { continue } else { let parsedValue = parse(generator) if let value = parsedValue.value { values.append(value) generator.replay() } else { return (nil, parsedValue.error) } } } } let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Unable to parse array. Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } enum NumberParsingState { case Initial case Whole case Decimal case Exponent case ExponentDigits } static func parseNumber<S: SequenceType where S.Generator.Element == UInt8>(generator: ReplayableGenerator<S>) -> JSParsingResult { var state = NumberParsingState.Initial var number = 0.0 var numberSign = 1.0 var depth = 0.1 var exponent = 0 var exponentSign = 1 for (idx, codeunit) in generator.enumerate() { switch (idx, codeunit, state) { case (0, Token.Minus, NumberParsingState.Initial): numberSign = -1 state = .Whole case (_, Token.Minus, NumberParsingState.Exponent): exponentSign = -1 state = .ExponentDigits case (_, Token.Plus, NumberParsingState.Initial): state = .Whole case (_, Token.Plus, NumberParsingState.Exponent): state = .ExponentDigits case (_, Token.Zero...Token.Nine, NumberParsingState.Initial): state = .Whole fallthrough case (_, Token.Zero...Token.Nine, NumberParsingState.Whole): number = number * 10 + Double(codeunit - Token.Zero) case (_, Token.Zero...Token.Nine, NumberParsingState.Decimal): number = number + depth * Double(codeunit - Token.Zero) depth /= 10 case (_, Token.Zero...Token.Nine, NumberParsingState.Exponent): state = .ExponentDigits fallthrough case (_, Token.Zero...Token.Nine, NumberParsingState.ExponentDigits): exponent = exponent * 10 + Int(codeunit) - Int(Token.Zero) case (_, Token.Period, NumberParsingState.Whole): state = .Decimal case (_, Token.e, NumberParsingState.Whole): state = .Exponent case (_, Token.E, NumberParsingState.Whole): state = .Exponent case (_, Token.e, NumberParsingState.Decimal): state = .Exponent case (_, Token.E, NumberParsingState.Decimal): state = .Exponent default: if codeunit.isValidTerminator() { return (JSValue(JSBackingValue.JSNumber(exp(number, exponent * exponentSign) * numberSign)), nil) } else { let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Unexpected token at index: \(idx). Token: \(codeunit). State: \(state). Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } } } if generator.atEnd() { return (JSValue(exp(number, exponent * exponentSign) * numberSign), nil) } let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Unable to parse array. Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } static func parseTrue<S: SequenceType where S.Generator.Element == UInt8>(generator: ReplayableGenerator<S>) -> JSParsingResult { for (idx, codeunit) in generator.enumerate() { switch (idx, codeunit) { case (0, Token.t): continue case (1, Token.r): continue case (2, Token.u): continue case (3, Token.e): continue case (4, _): if codeunit.isValidTerminator() { return (JSValue(true), nil) } fallthrough default: let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Unexpected token at index: \(idx). Token: \(codeunit). Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } } if generator.atEnd() { return (JSValue(true), nil) } let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Unable to parse 'true' literal. Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } static func parseFalse<S: SequenceType where S.Generator.Element == UInt8>(generator: ReplayableGenerator<S>) -> JSParsingResult { for (idx, codeunit) in generator.enumerate() { switch (idx, codeunit) { case (0, Token.f): continue case (1, Token.a): continue case (2, Token.l): continue case (3, Token.s): continue case (4, Token.e): continue case (5, _): if codeunit.isValidTerminator() { return (JSValue(false), nil) } fallthrough default: let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Unexpected token at index: \(idx). Token: \(codeunit). Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } } if generator.atEnd() { return (JSValue(false), nil) } let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Unable to parse 'false' literal. Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } static func parseNull<S: SequenceType where S.Generator.Element == UInt8>(generator: ReplayableGenerator<S>) -> JSParsingResult { for (idx, codeunit) in generator.enumerate() { switch (idx, codeunit) { case (0, Token.n): continue case (1, Token.u): continue case (2, Token.l): continue case (3, Token.l): continue case (4, _): if codeunit.isValidTerminator() { return (JSValue(JSBackingValue.JSNull), nil) } fallthrough default: let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Unexpected token at index: \(idx). Token: \(codeunit). Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } } if generator.atEnd() { return (JSValue(JSBackingValue.JSNull), nil) } let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Unable to parse 'null' literal. Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } private static func parseHexDigit(digit: UInt8) -> Int? { if Token.Zero <= digit && digit <= Token.Nine { return Int(digit) - Int(Token.Zero) } else if Token.a <= digit && digit <= Token.f { return 10 + Int(digit) - Int(Token.a) } else if Token.A <= digit && digit <= Token.F { return 10 + Int(digit) - Int(Token.A) } else { return nil } } static func parseString<S: SequenceType where S.Generator.Element == UInt8>(generator: ReplayableGenerator<S>, quote: UInt8) -> JSParsingResult { var bytes = [UInt8]() for (idx, codeunit) in generator.enumerate() { switch (idx, codeunit) { case (0, quote): continue case (_, quote): generator.next() // eat the quote bytes.append(0) let ptr = UnsafePointer<CChar>(bytes) if let string = String.fromCString(ptr) { return (JSValue(string), nil) } else { let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Unable to convert the parsed bytes into a string. Bytes: \(bytes)'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } case (_, Token.Backslash): let next = generator.next() if let next = next { switch next { case Token.Backslash: bytes.append(Token.Backslash) case Token.Forwardslash: bytes.append(Token.Forwardslash) case quote: bytes.append(Token.DoubleQuote) case Token.n: bytes.append(Token.Linefeed) case Token.b: bytes.append(Token.Backspace) case Token.f: bytes.append(Token.Formfeed) case Token.r: bytes.append(Token.CarriageReturn) case Token.t: bytes.append(Token.HorizontalTab) case Token.u: let c1 = generator.next() let c2 = generator.next() let c3 = generator.next() let c4 = generator.next() switch (c1, c2, c3, c4) { case let (.Some(c1), .Some(c2), .Some(c3), .Some(c4)): let value1 = parseHexDigit(c1) let value2 = parseHexDigit(c2) let value3 = parseHexDigit(c3) let value4 = parseHexDigit(c4) if value1 == nil || value2 == nil || value3 == nil || value4 == nil { let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Invalid unicode escape sequence"] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } let codepoint = (value1! << 12) | (value2! << 8) | (value3! << 4) | value4!; let character = String(UnicodeScalar(codepoint)) let data = character.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! let ptr = UnsafePointer<UInt8>(data.bytes) let escapeBytes = UnsafeBufferPointer<UInt8>(start: ptr, count: data.length) bytes.extend(escapeBytes) default: let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Invalid unicode escape sequence"] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } default: let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Unexpected token at index: \(idx + 1). Token: \(next). Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } } else { let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Unexpected token at index: \(idx). Token: \(codeunit). Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } default: bytes.append(codeunit) } } let info = [ ErrorKeys.LocalizedDescription: ErrorCode.ParsingError.message, ErrorKeys.LocalizedFailureReason: "Unable to parse string. Context: '\(contextualString(generator))'."] return (nil, Error(code: ErrorCode.ParsingError.code, domain: JSValueErrorDomain, userInfo: info)) } // MARK: Helper functions static func substring<S: SequenceType where S.Generator.Element == UInt8>(generator: ReplayableGenerator<S>) -> String { var string = "" for codeunit in generator { string += String(codeunit) } return string } static func contextualString<S: SequenceType where S.Generator.Element == UInt8>(generator: ReplayableGenerator<S>, left: Int = 5, right: Int = 10) -> String { var string = "" for var i = left; i > 0; i-- { generator.replay() } for var i = 0; i < (left + right); i++ { let codeunit = generator.next() ?? 0 string += String(codeunit) } return string } static func exp(number: Double, _ exp: Int) -> Double { return exp < 0 ? (0 ..< abs(exp)).reduce(number, combine: { x, _ in x / 10 }) : (0 ..< exp).reduce(number, combine: { x, _ in x * 10 }) } } extension UInt8 { /// Determines if the `UnicodeScalar` represents one of the standard Unicode whitespace characters. /// /// :return: `true` if the scalar is a Unicode whitespace character; `false` otherwise. func isWhitespace() -> Bool { if self >= 0x09 && self <= 0x0D { return true } // White_Space # Cc [5] <control-0009>..<control-000D> if self == 0x20 { return true } // White_Space # Zs SPACE if self == 0x85 { return true } // White_Space # Cc <control-0085> if self == 0xA0 { return true } // White_Space # Zs NO-BREAK SPACE // TODO: These are no longer possible to be hit... does it matter??? // if self == 0x1680 { return true } // White_Space # Zs OGHAM SPACE MARK // if self >= 0x2000 && self <= 0x200A { return true } // White_Space # Zs [11] EN QUAD..HAIR SPACE // if self == 0x2028 { return true } // White_Space # Zl LINE SEPARATOR // if self == 0x2029 { return true } // White_Space # Zp PARAGRAPH SEPARATOR // if self == 0x202F { return true } // White_Space # Zs NARROW NO-BREAK SPACE // if self == 0x205F { return true } // White_Space # Zs MEDIUM MATHEMATICAL SPACE // if self == 0x3000 { return true } // White_Space # Zs IDEOGRAPHIC SPACE return false } /// Determines if the `UnicodeScalar` respresents a numeric digit. /// /// :return: `true` if the scalar is a Unicode numeric character; `false` otherwise. func isDigit() -> Bool { return self >= Token.Zero && self <= Token.Nine } /// Determines if the `UnicodeScalar` respresents a valid terminating character. /// :return: `true` if the scalar is a valid terminator, `false` otherwise. func isValidTerminator() -> Bool { if self == Token.Comma { return true } if self == Token.RightBracket { return true } if self == Token.RightCurly { return true } if self.isWhitespace() { return true } return false } // /// Stores the `UInt8` bytes that make up the UTF8 code points for the scalar. // /// // /// :param: buffer the buffer to write the UTF8 code points into. // func utf8(inout buffer: [UInt8]) { // /* // * This implementation should probably be replaced by the function below. However, // * I am not quite sure how to properly use `SinkType` yet... // * // * UTF8.encode(input: UnicodeScalar, output: &S) // */ // // if value <= 0x007F { // buffer.append(UInt8(value)) // } // else if 0x0080 <= value && value <= 0x07FF { // buffer.append(UInt8(value &/ 64) &+ 192) // buffer.append(UInt8(value &% 64) &+ 128) // } // else if (0x0800 <= value && value <= 0xD7FF) || (0xE000 <= value && value <= 0xFFFF) { // buffer.append(UInt8(value &/ 4096) &+ 224) // buffer.append(UInt8((value &% 4096) &/ 64) &+ 128) // buffer.append(UInt8(value &% 64 &+ 128)) // } // else { // buffer.append(UInt8(value &/ 262144) &+ 240) // buffer.append(UInt8((value &% 262144) &/ 4096) &+ 128) // buffer.append(UInt8((value &% 4096) &/ 64) &+ 128) // buffer.append(UInt8(value &% 64) &+ 128) // } // } } /// The code unit value for all of the token characters used. struct Token { private init() {} // Control Codes static let Linefeed = UInt8(10) static let Backspace = UInt8(8) static let Formfeed = UInt8(12) static let CarriageReturn = UInt8(13) static let HorizontalTab = UInt8(9) // Tokens for JSON static let LeftBracket = UInt8(91) static let RightBracket = UInt8(93) static let LeftCurly = UInt8(123) static let RightCurly = UInt8(125) static let Comma = UInt8(44) static let SingleQuote = UInt8(39) static let DoubleQuote = UInt8(34) static let Minus = UInt8(45) static let Plus = UInt8(43) static let Backslash = UInt8(92) static let Forwardslash = UInt8(47) static let Colon = UInt8(58) static let Period = UInt8(46) // Numbers static let Zero = UInt8(48) static let One = UInt8(49) static let Two = UInt8(50) static let Three = UInt8(51) static let Four = UInt8(52) static let Five = UInt8(53) static let Six = UInt8(54) static let Seven = UInt8(55) static let Eight = UInt8(56) static let Nine = UInt8(57) // Character tokens for JSON static let A = UInt8(65) static let E = UInt8(69) static let F = UInt8(70) static let a = UInt8(97) static let b = UInt8(98) static let e = UInt8(101) static let f = UInt8(102) static let l = UInt8(108) static let n = UInt8(110) static let r = UInt8(114) static let s = UInt8(115) static let t = UInt8(116) static let u = UInt8(117) }
mit
09666eef5f1344295064be6bb73d7f60
43.217066
183
0.529945
4.839751
false
false
false
false
kstaring/swift
test/IRGen/Inputs/ObjectiveC.swift
30
1187
// This is an overlay Swift module. @_exported import ObjectiveC public struct ObjCBool : CustomStringConvertible { #if os(OSX) || (os(iOS) && (arch(i386) || arch(arm))) // On OS X and 32-bit iOS, Objective-C's BOOL type is a "signed char". private var value: Int8 public init(_ value: Bool) { self.value = value ? 1 : 0 } /// \brief Allow use in a Boolean context. public var boolValue: Bool { return value != 0 } #else // Everywhere else it is C/C++'s "Bool" private var value: Bool public init(_ value: Bool) { self.value = value } public var boolValue: Bool { return value } #endif public var description: String { // Dispatch to Bool. return self.boolValue.description } } public struct Selector { private var ptr : OpaquePointer } // Functions used to implicitly bridge ObjCBool types to Swift's Bool type. public func _convertBoolToObjCBool(_ x: Bool) -> ObjCBool { return ObjCBool(x) } public func _convertObjCBoolToBool(_ x: ObjCBool) -> Bool { return x.boolValue } extension NSObject : Hashable { open var hashValue: Int { return 0 } } public func ==(x: NSObject, y: NSObject) -> Bool { return x === y }
apache-2.0
168d212eb5e839c7a94af3b65d304688
21.396226
75
0.666386
3.756329
false
false
false
false
SteveRohrlack/CitySimCore
src/Model/City/CityMap.swift
1
7835
/// /// CityMap.swift /// CitySimCore /// /// Created by Steve Rohrlack on 13.05.16. /// Copyright © 2016 Steve Rohrlack. All rights reserved. /// import Foundation import GameplayKit /** CityMap encapsules all aspects of working with the simulation's underlying map data. It provides a high level api to add and remove tiles. The CityMap consist of multiple layers - TileLayer holding all visible tiles - StatisticlayersContainer holding all statistical layers Additionaly, the CityMap contains a Graph representation of Locations that are RessourceCyrrying. CityMap emits events, see CityMapEvent: - AddTile: when a tile was successfully added, payload: new tile - RemoveTile: when a tile was successfully removed, payload: removed tile */ public struct CityMap: EventEmitting { typealias EventNameType = CityMapEvent /// Container holding event subscribers var eventSubscribers: [EventNameType: [EventSubscribing]] = [:] /// height of the map / height of all layers public private(set) var height: Int /// width of the map / width of all layers public private(set) var width: Int /// the tile layer public var tileLayer: TileLayer /// Container holding statistical layers public var statisticsLayerContainer: StatisticlayersContainer /// pathfinding graph var trafficLayer: GKGridGraph /** Constructur - parameter height: height of the map / height of all layers - parameter width: width of the map / width of all layers */ init(height: Int, width: Int) { self.width = width self.height = height self.tileLayer = TileLayer(rows: height, columns: width) self.statisticsLayerContainer = StatisticlayersContainer(height: height, width: width) self.trafficLayer = GKGridGraph(fromGridStartingAt: vector_int2(0, 0), width: Int32(width), height: Int32(height), diagonalsAllowed: false) //empty graph if let nodes = self.trafficLayer.nodes { self.trafficLayer.removeNodes(nodes) } } // MARK: add, remove /** convenience method to check if a tile can be added to the tile layer also checks dependencies for tiles to be added: must be placed near road - parameter tile: tile to be added throws: CityMapError.TileCantFit if the new tile doesn't fit into the tile layer throws: CityMapError.CannotAddBecauseNotEmpty if the desired tile location is already in use throws: CityMapError.PlaceNearStreet if the tile should be placed adjecant to a street ploppable and isn't */ func canAdd(tile newTile: Tileable) throws { /// check if new tile can fit into the map guard newTile.originY >= 0 && newTile.originX >= 0 && newTile.maxY < height && newTile.maxX < width else { throw CityMapError.TileCantFit } /// check if desired location is already in use let locationUsedByTiles = tileLayer.usedByTilesAt(location: newTile) guard locationUsedByTiles.count == 0 else { throw CityMapError.CannotAddBecauseNotEmpty } /// check if tile should be placed near a street guard newTile is PlaceNearStreet else { return } let check = newTile + 1 let checkLocationUsedByTiles = tileLayer.usedByTilesAt(location: check) let adjecantStreet = checkLocationUsedByTiles.contains { (tile: Tileable) in guard case .Ploppable(let ploppType) = tile.type where ploppType == .Street else { return false } return true } if !adjecantStreet { throw CityMapError.PlaceNearStreet } } /** private method to add a tile - parameter tile: the tile to be added emits the event "AddTile" throws: TileLayerError if there was a problem throws: unspecified error if the event "AddTile" throws */ private mutating func add(tile tile: Tileable) throws { try canAdd(tile: tile) try tileLayer.add(tile: tile) /// adding map statistics for supporting tile if let mapStatistical = tile as? MapStatistical { statisticsLayerContainer.addStatistics( at: tile, statistical: mapStatistical ) } /// adding graph nodes for supporting tile if tile is RessourceCarrying { trafficLayer.add(location: tile) } /// emit event try emit(event: CityMapEvent.AddTile, payload: tile) } // MARK: remove, info /** checks if removing all tiles specified by the given location is possible - parameter location: location throws CityMapError.TileNotRemoveable if a tile requested to be removed is of type "TileNotRemoveable" */ public func canRemoveAt(location location: Locateable) throws { let tilesToRemove = tileLayer.usedByTilesAt(location: location) for tile in tilesToRemove { if tile is NotRemoveable { throw CityMapError.TileNotRemoveable } } } /** removes all tiles specified by the given location - parameter location: location emits the event "RemoveTile" throws CityMapError.TileNotRemoveable if a tile requested to be removed is of type "TileNotRemoveable" throws: unspecified error if the event "RemoveTile" throws */ public mutating func removeAt(location location: Locateable) throws { let tilesToRemove = tileLayer.usedByTilesAt(location: location) for tile in tilesToRemove { if tile is NotRemoveable { throw CityMapError.TileNotRemoveable } tileLayer.remove(tile: tile) /// removing map statistics for supporting tile if let mapStatistical = tile as? MapStatistical { statisticsLayerContainer.removeStatistics( at: tile, statistical: mapStatistical ) } /// removing graph nodes for supporting tile if tile is RessourceCarrying { trafficLayer.remove(location: tile) } /// emit event try emit(event: CityMapEvent.RemoveTile, payload: tile) } } /** convenience method to retrieve a list of tiles specified by the given location - parameter location: location - returns: list of tiles contained in location */ public func infoAt(location location: Locateable) -> [Tileable] { return tileLayer.usedByTilesAt(location: location) } // MARK: zone, plopp, prop /** add a "Zone" (zoneable) to the tile layer - parameter zone: the zone to add throws: TileLayerError if there was a problem */ public mutating func zone(zone zone: Zoneable) throws { try add(tile: zone) } /** add a "Plopp" (ploppable) to the tile layer - parameter plopp: the ploppable to add throws: TileLayerError if there was a problem */ public mutating func plopp(plopp plopp: Ploppable) throws { try add(tile: plopp) } /** add a "Prop" (propable) to the tile layer - parameter prop: the propable to add throws: TileLayerError if there was a problem */ public mutating func prop(prop prop: Propable) throws { try add(tile: prop) } }
mit
918b8b763d0d9c8ecc299183e482c822
29.964427
147
0.620883
4.733535
false
false
false
false
mightydeveloper/swift
test/Parse/compiler_version.swift
10
2446
// RUN: %target-parse-verify-swift #if _compiler_version("999.*.999.999.999") let w = 1 #else // This shouldn't emit any diagnostics. asdf asdf asdf asdf #endif #if _compiler_version("10.*.10.10") #if os(iOS) let z = 1 #else let z = 1 #endif #else // This shouldn't emit any diagnostics. asdf asdf asdf asdf #if os(iOS) // This shouldn't emit any diagnostics. asdf asdf asdf asdf #else // This shouldn't emit any diagnostics. asdf asdf asdf asdf #endif // This shouldn't emit any diagnostics. asdf asdf asdf asdf #endif #if !_compiler_version("777.*.7") // This shouldn't emit any diagnostics. $#%^*& #endif #if _compiler_version("700a.*.10") // expected-error {{compiler version component is not a number}} #endif #if _compiler_version("...") // expected-error {{found empty compiler version component}} // expected-error@-1 {{found empty compiler version component}} // expected-error@-2 {{found empty compiler version component}} #endif #if _compiler_version("") // expected-error {{compiler version requirement is empty}} let y = 1 #else let thisWillStillParseBecauseConfigIsError = 1 #endif #if _compiler_version("10.*.10.10") && os(iOS) // expected-error {{cannot combine _compiler_version with binary operators}} #endif #if _compiler_version("10.*.10.10") || os(iOS) // expected-error {{cannot combine _compiler_version with binary operators}} #endif #if os(iOS) && _compiler_version("10.*.10.10") // expected-error {{cannot combine _compiler_version with binary operators}} #endif #if os(iOS) || _compiler_version("10.*.10.10") // expected-error {{cannot combine _compiler_version with binary operators}} #endif #if _compiler_version("700.0.100") // expected-warning {{the second version component is not used for comparison}} #endif #if _compiler_version("700.*.1.1.1.1") // expected-error {{compiler version must not have more than five components}} #endif #if _compiler_version("9223372.*.1.1.1") // expected-error {{compiler version component out of range: must be in [0, 9223371]}} #endif #if _compiler_version("700.*.1000.1.1") // expected-error {{compiler version component out of range: must be in [0, 999]}} #endif #if _compiler_version("700.*.1.1000.1") // expected-error {{compiler version component out of range: must be in [0, 999]}} #endif #if _compiler_version("700.*.1.1.1000") // expected-error {{compiler version component out of range: must be in [0, 999]}} #endif
apache-2.0
0fc6d2285eb80c09d6e7958204b1b3a5
29.962025
127
0.697874
3.27882
false
false
false
false
jeffreybergier/FruitKey
FKKeyboard/KeyboardViewController.swift
1
10724
// // KeyboardViewController.swift // FKKeyboard // // Created by Jeffrey Bergier on 10/29/14. // // The MIT License (MIT) // // Copyright (c) 2014 Jeffrey Bergier // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class KeyboardViewController: UIInputViewController { private var keyboardView: FKKeyboardView? private weak var castedTextDocumentProxy: UITextDocumentProxy? private var keyboardHeight: CGFloat = 50.0 private let IPHONE5KEYBOARDHEIGHT: CGFloat = 101.0 private let IPHONE6KEYBOARDHEIGHT: CGFloat = 50.0 private let IPADKEYBOARDHEIGHT: CGFloat = 71.0 private let KEYBOARDGOAWAYTIMERINTERVAL = 0.0 private let KEYBOARDGOINGAWAYANIMATIONDURATION = 0.2 private let KEYBOARDKEYZOOMINGANIMATIONDURATION = 0.4 private var heightConstraint: NSLayoutConstraint? override func updateViewConstraints() { super.updateViewConstraints() // Add custom view sizing constraints here } override func viewDidLoad() { super.viewDidLoad() //it should be easier to deal with this pre-casted textDocumentProxy self.castedTextDocumentProxy = self.textDocumentProxy as? UITextDocumentProxy //check screensize self.keyboardHeight = self.checkScreenSize() //create the view and add it to the view controller let nibArray:NSArray = NSBundle.mainBundle().loadNibNamed("FKKeyboardView", owner: self, options: nil) for i in 0..<nibArray.count { if let keyboardView = nibArray[i] as? FKKeyboardView { if keyboardView.frame.size.height == self.keyboardHeight { self.keyboardView = keyboardView break } } } //check if this is an iPad if self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.Regular && self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.Regular { self.keyboardHeight = self.IPADKEYBOARDHEIGHT } if let keyboardView = self.keyboardView { keyboardView.setTranslatesAutoresizingMaskIntoConstraints(false) self.view.addSubview(keyboardView) var keyboardViewLeftSideConstraint = NSLayoutConstraint(item: keyboardView, attribute: .Left, relatedBy: .Equal, toItem: self.view, attribute: .Left, multiplier: 1.0, constant: 0.0) var keyboardViewRightSideConstraint = NSLayoutConstraint(item: keyboardView, attribute: .Right, relatedBy: .Equal, toItem: self.view, attribute: .Right, multiplier: 1.0, constant: 0.0) var keyboardViewTopConstraint = NSLayoutConstraint(item: keyboardView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1.0, constant: 0.0) var keyboardViewBottomConstraint = NSLayoutConstraint(item: keyboardView, attribute: .Bottom, relatedBy: .Equal, toItem: self.view, attribute: .Bottom, multiplier: 1.0, constant: 0.0) self.view.addConstraints([keyboardViewLeftSideConstraint, keyboardViewRightSideConstraint, keyboardViewTopConstraint, keyboardViewBottomConstraint]) keyboardView.delegate = self } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) //set the height of the keyboard if let heightConstraint = self.heightConstraint { println("KeyboardViewController: The height constraint was already set on viewwillappear. This probably shouldn't happen") } else { let variable = self.keyboardHeight self.heightConstraint = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 0.0, constant: self.keyboardHeight) self.view.addConstraint(self.heightConstraint!) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated } override func textWillChange(textInput: UITextInput) { // The app is about to change the document's contents. Perform any preparation here. } override func textDidChange(textInput: UITextInput?) { // The app has just changed the document's contents, the document context has been updated. if let castedTextDocumentProxy = self.castedTextDocumentProxy { if castedTextDocumentProxy.keyboardAppearance == UIKeyboardAppearance.Dark { NSNotificationCenter.defaultCenter().postNotificationName("keyboardShouldBeDark", object: self) } else { NSNotificationCenter.defaultCenter().postNotificationName("keyboardShouldBeLight", object: self) } } } //handle the button presses from the view func didTapChangeKeyboardButton(sender:FKKeyboardKeyButton) { self.advanceToNextInputMode() } func didTapInsertWatchKeyboardButton(sender:FKKeyboardKeyButton) { let stringToBeInserted = self.checkCurrentContext() self.castedTextDocumentProxy?.insertText(stringToBeInserted + "Watch ") self.animatedPressedButton(sender, AndStartTimer: true) } func didTapInsertTVKeyboardButton(sender:FKKeyboardKeyButton) { let stringToBeInserted = self.checkCurrentContext() self.castedTextDocumentProxy?.insertText(stringToBeInserted + "TV ") self.animatedPressedButton(sender, AndStartTimer: true) } func didTapInsertPayKeyboardButton(sender:FKKeyboardKeyButton) { let stringToBeInserted = self.checkCurrentContext() self.castedTextDocumentProxy?.insertText(stringToBeInserted + "Pay ") self.animatedPressedButton(sender, AndStartTimer: true) } func didTapInsertAppleKeyboardButton(sender:FKKeyboardKeyButton) { let stringToBeInserted = self.checkCurrentContext() self.castedTextDocumentProxy?.insertText(stringToBeInserted + "") self.animatedPressedButton(sender, AndStartTimer: true) } private func checkCurrentContext() -> String { var string = "" if let textDocumentProxy = self.castedTextDocumentProxy { let stringBeforeInput:NSString? = textDocumentProxy.documentContextBeforeInput //if this context before input is nil that means we're at the beginning of the line. No space is needed. The next optional unwrap will be skipped and we will return a blank string if let stringBeforeInput = stringBeforeInput { //if the string is not nil we need to figure out which character is there. If its a space, then we insert nothing. If its anything else, we insert a space. if stringBeforeInput.characterAtIndex(stringBeforeInput.length - 1) != 32 { string = " " } } } return string } private func animatedPressedButton(sender: FKKeyboardKeyButton, AndStartTimer startTimer: Bool) { sender.superview?.bringSubviewToFront(sender) UIView.animateWithDuration(self.KEYBOARDKEYZOOMINGANIMATIONDURATION, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { sender.transform = CGAffineTransformScale(sender.transform, 2.0, 2.0) sender.alpha = 0.0 sender.superview?.alpha = 1.0 }, completion: { finished in if (startTimer) { let timer = NSTimer.scheduledTimerWithTimeInterval(self.KEYBOARDGOAWAYTIMERINTERVAL, target: self, selector: "animateAwayKeyboardAndSwitchToNextKeyboard:", userInfo: nil, repeats: false) } else { self.advanceToNextInputMode() } }) } func animateAwayKeyboardAndSwitchToNextKeyboard(timer: NSTimer) { timer.invalidate() if let keyboardView = self.keyboardView { UIView.animateWithDuration(self.KEYBOARDGOINGAWAYANIMATIONDURATION, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 1.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { keyboardView.transform = CGAffineTransformTranslate(keyboardView.transform, 0.0, keyboardView.frame.size.height) keyboardView.alpha = 0.0 }, completion: { finished in self.advanceToNextInputMode() }) } } private func checkScreenSize() -> CGFloat { var keyboardHeight:CGFloat = 0.0 if UIScreen.mainScreen().bounds.size.height > UIScreen.mainScreen().bounds.size.width { //portrait phone if UIScreen.mainScreen().bounds.size.width > 321 { //iphone 6 or 6+ keyboardHeight = self.IPHONE6KEYBOARDHEIGHT } else { //iphone 4S or 5 keyboardHeight = self.IPHONE5KEYBOARDHEIGHT } } else { //landscape phone if UIScreen.mainScreen().bounds.size.height > 321 { //iphone 6 or 6+ keyboardHeight = self.IPHONE6KEYBOARDHEIGHT } else { //iphone 4S or 5 keyboardHeight = self.IPHONE5KEYBOARDHEIGHT } } return keyboardHeight } }
mit
4a12eb3bcfe4fbb3c006bfbb901db3f6
45.189655
249
0.669093
5.28924
false
false
false
false
huangboju/QMUI.swift
QMUI.swift/QMUIKit/UIComponents/ImagePickerLibrary/QMUIImagePickerCollectionViewCell.swift
1
8425
// // QMUIImagePickerCollectionViewCell.swift // QMUI.swift // // Created by 黄伯驹 on 2017/7/10. // Copyright © 2017年 伯驹 黄. All rights reserved. // // checkbox 的 margin 默认值 let QMUIImagePickerCollectionViewCellDefaultCheckboxButtonMargins = UIEdgeInsets(top: 6, left: 0, bottom: 0, right: 6) private let QMUIImagePickerCollectionViewCellDefaultVideoMarkImageViewMargins = UIEdgeInsets(top: 0, left: 8, bottom: 8, right: 0) /** * 图片选择空间里的九宫格 cell,支持显示 checkbox、饼状进度条及重试按钮(iCloud 图片需要) */ class QMUIImagePickerCollectionViewCell: UICollectionViewCell { /// checkbox 未被选中时显示的图片 var checkboxImage: UIImage! { didSet { if checkboxImage != oldValue { checkboxButton.setImage(checkboxImage, for: .normal) checkboxButton.sizeToFit() } } } /// checkbox 被选中时显示的图片 var checkboxCheckedImage: UIImage! { didSet { if checkboxCheckedImage != oldValue { checkboxButton.setImage(checkboxCheckedImage, for: .selected) checkboxButton.setImage(checkboxCheckedImage, for: [.selected, .highlighted]) checkboxButton.sizeToFit() } } } /// checkbox 的 margin,定位从每个 cell(即每张图片)的最右边开始计算 var checkboxButtonMargins = QMUIImagePickerCollectionViewCellDefaultCheckboxButtonMargins /// videoMarkImageView 的 icon var videoMarkImage: UIImage! = QMUIHelper.image(name: "QMUI_pickerImage_video_mark") { didSet { if videoMarkImage != oldValue { videoMarkImageView?.image = videoMarkImage videoMarkImageView?.sizeToFit() } } } /// videoMarkImageView 的 margin,定位从每个 cell(即每张图片)的左下角开始计算 var videoMarkImageViewMargins: UIEdgeInsets = QMUIImagePickerCollectionViewCellDefaultVideoMarkImageViewMargins /// videoDurationLabel 的字号 var videoDurationLabelFont: UIFont = UIFontMake(12) { didSet { if videoDurationLabelFont != oldValue { videoDurationLabel?.font = videoDurationLabelFont videoDurationLabel?.qmui_calculateHeightAfterSetAppearance() } } } /// videoDurationLabel 的字体颜色 var videoDurationLabelTextColor: UIColor = UIColorWhite { didSet { if videoDurationLabelTextColor != oldValue { videoDurationLabel?.textColor = videoDurationLabelTextColor } } } /// videoDurationLabel 布局是对齐右下角再做 margins 偏移 var videoDurationLabelMargins: UIEdgeInsets = UIEdgeInsets(top: 0, left: 0, bottom: 6, right: 6) private(set) var contentImageView: UIImageView! private(set) var checkboxButton: UIButton! private var _videoMarkImageView: UIImageView? var videoMarkImageView: UIImageView? { initVideoRelatedViewsIfNeeded() return _videoMarkImageView } private var _videoDurationLabel: UILabel? var videoDurationLabel: UILabel? { initVideoRelatedViewsIfNeeded() return _videoDurationLabel } private var _videoBottomShadowLayer: CAGradientLayer? var videoBottomShadowLayer: CAGradientLayer? { initVideoRelatedViewsIfNeeded() return _videoBottomShadowLayer } var isSelectable: Bool = false { didSet { if downloadStatus == .succeed { checkboxButton.isHidden = !isSelectable } } } var isChecked: Bool = false { didSet { if isSelectable { checkboxButton.isSelected = isChecked QMUIImagePickerHelper.removeSpringAnimationOfImageChecked(with: checkboxButton) if isChecked { QMUIImagePickerHelper.springAnimationOfImageChecked(with: checkboxButton) } } } } // Cell 中对应资源的下载状态,这个值的变动会相应地调整 UI 表现 var downloadStatus: QMUIAssetDownloadStatus = .succeed { didSet { if isSelectable { checkboxButton.isHidden = !isSelectable } } } var assetIdentifier: String? // 当前这个 cell 正在展示的 QMUIAsset 的 identifier override init(frame: CGRect) { super.init(frame: frame) initImagePickerCollectionViewCellUI() } private func initImagePickerCollectionViewCellUI() { contentImageView = UIImageView() contentImageView.contentMode = .scaleAspectFill contentImageView.clipsToBounds = true contentView.addSubview(contentImageView) checkboxButton = QMUIButton() checkboxButton.qmui_automaticallyAdjustTouchHighlightedInScrollView = true checkboxButton.qmui_outsideEdge = UIEdgeInsets(top: -6, left: -6, bottom: -6, right: -6) checkboxButton.isHidden = true contentView.addSubview(checkboxButton) checkboxImage = QMUIHelper.image(name: "QMUI_pickerImage_checkbox") checkboxCheckedImage = QMUIHelper.image(name: "QMUI_pickerImage_checkbox_checked") } private func initVideoBottomShadowLayerIfNeeded() { if _videoBottomShadowLayer == nil { _videoBottomShadowLayer = CAGradientLayer() _videoBottomShadowLayer!.qmui_removeDefaultAnimations() _videoBottomShadowLayer!.colors = [ UIColor(r: 0, g: 0, b: 0).cgColor, UIColor(r: 0, g: 0, b: 0, a: 0.6).cgColor, ] contentView.layer.addSublayer(_videoBottomShadowLayer!) setNeedsLayout() } } private func initVideoMarkImageViewIfNeed() { if _videoMarkImageView != nil { return } _videoMarkImageView = UIImageView() _videoMarkImageView?.image = videoMarkImage _videoMarkImageView?.sizeToFit() contentView.addSubview(_videoMarkImageView!) setNeedsLayout() } private func initVideoDurationLabelIfNeed() { if _videoDurationLabel != nil { return } _videoDurationLabel = UILabel() _videoDurationLabel?.font = videoDurationLabelFont _videoDurationLabel?.textColor = videoDurationLabelTextColor contentView.addSubview(_videoDurationLabel!) setNeedsLayout() } private func initVideoRelatedViewsIfNeeded() { initVideoBottomShadowLayerIfNeeded() initVideoMarkImageViewIfNeed() initVideoDurationLabelIfNeed() } override func layoutSubviews() { super.layoutSubviews() contentImageView.frame = contentView.bounds if isSelectable { checkboxButton.frame = checkboxButton.frame.setXY(contentView.bounds.width - checkboxButtonMargins.right - checkboxButton.frame.width, checkboxButtonMargins.top) } if let videoBottomShadowLayer = _videoBottomShadowLayer, let videoMarkImageView = _videoMarkImageView, let videoDurationLabel = _videoDurationLabel { videoMarkImageView.frame = videoMarkImageView.frame.setXY(videoMarkImageViewMargins.left, contentView.bounds.height - videoMarkImageView.bounds.height - videoMarkImageViewMargins.bottom) videoDurationLabel.sizeToFit() let minX = contentView.bounds.width - videoDurationLabelMargins.right - videoDurationLabel.bounds.width let minY = contentView.bounds.height - videoDurationLabelMargins.bottom - videoDurationLabel.bounds.height videoDurationLabel.frame = videoDurationLabel.frame.setXY(minX, minY) let videoBottomShadowLayerHeight = contentView.bounds.height - videoMarkImageView.frame.minY + videoMarkImageViewMargins.bottom // 背景阴影遮罩的高度取决于(视频 icon 的高度 + 上下 margin) videoBottomShadowLayer.frame = CGRectFlat(0, contentView.bounds.height - videoBottomShadowLayerHeight, contentView.bounds.width, videoBottomShadowLayerHeight) } } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
f133d054269a4791aabe86eb65b7d167
35.785388
198
0.65926
5.150895
false
false
false
false
handsomecode/InteractiveSideMenu
Sources/MenuTransitioningDelegate.swift
1
2133
// // MenuTransitioningDelegate.swift // // Copyright 2017 Handsome 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 /** Delegate of menu transitioning actions. */ final class MenuTransitioningDelegate: NSObject { let interactiveTransition: MenuInteractiveTransition public var currentItemOptions = SideMenuItemOptions() { didSet { interactiveTransition.currentItemOptions = currentItemOptions } } init(interactiveTransition: MenuInteractiveTransition) { self.interactiveTransition = interactiveTransition } } extension MenuTransitioningDelegate: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { interactiveTransition.present = true return interactiveTransition } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { interactiveTransition.present = false return interactiveTransition } func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactiveTransition.interactionInProgress ? interactiveTransition : nil } func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactiveTransition.interactionInProgress ? interactiveTransition : nil } }
apache-2.0
aad714f3e4effd5f6fd0d0e79c544ac2
35.775862
170
0.773558
6.310651
false
false
false
false
linhaosunny/smallGifts
小礼品/小礼品/Classes/Module/Classify/Controllers/SingleGiftViewController.swift
1
8127
// // SingleGiftViewController.swift // 小礼品 // // Created by 李莎鑫 on 2017/4/21. // Copyright © 2017年 李莎鑫. All rights reserved. // import UIKit import SnapKit fileprivate let cellColumns = 3 fileprivate let cellScale:CGFloat = 100.0 / 140.0 fileprivate let scale = 0.25 class SingleGiftViewController: UIViewController { fileprivate let singleGiftColumnIndentifier = "singleGiftColumnCell" fileprivate let singleGiftIndentifier = "singleGiftCell" fileprivate let singleGiftSectionIndentifier = "singleGiftSectionCell" fileprivate var isSelectedColumn = false fileprivate var selectedColumnRow = 0 //MARK: 懒加载 lazy var tableView:UITableView = { () -> UITableView in let view = UITableView(frame: CGRect.zero, style: .plain) view.backgroundColor = SystemGlobalBackgroundColor view.separatorStyle = .none view.showsHorizontalScrollIndicator = false view.showsVerticalScrollIndicator = false view.sectionFooterHeight = 0.0001 view.sectionHeaderHeight = 0.0001 view.delegate = self view.dataSource = self view.register(SingleGiftColumnCell.self , forCellReuseIdentifier: self.singleGiftColumnIndentifier) return view }() lazy var collectionView:UICollectionView = { () -> UICollectionView in let view = UICollectionView(frame: CGRect.zero, collectionViewLayout: SingleGiftViewFlowLayout()) view.backgroundColor = UIColor.white view.showsVerticalScrollIndicator = false view.showsHorizontalScrollIndicator = false view.dataSource = self view.delegate = self view.register(SingleGiftCell.self, forCellWithReuseIdentifier: self.singleGiftIndentifier) view.register(SingleGiftSectionView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: self.singleGiftSectionIndentifier) return view }() //MARK: 系统方法 override func viewDidLoad() { super.viewDidLoad() setupSingleGiftView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() setupSingleGiftViewSubView() } //MARK: 私有方法 private func setupSingleGiftView() { view.backgroundColor = UIColor.white view.addSubview(tableView) view.addSubview(collectionView) } private func setupSingleGiftViewSubView() { tableView.snp.makeConstraints { (make) in make.left.top.bottom.equalToSuperview() make.width.equalToSuperview().multipliedBy(scale) } collectionView.snp.makeConstraints { (make) in make.left.equalTo(tableView.snp.right) make.top.right.bottom.equalToSuperview() } } fileprivate func tableViewScrollToAt(indexPath:IndexPath) { guard let cell = tableView.cellForRow(at: indexPath) else { return } if cell.center.y < tableView.bounds.height * 0.5 { tableView.setContentOffset(CGPoint.zero, animated: true) } //: 滚动按钮居中 else if (tableView.contentSize.height > tableView.bounds.height) && (cell.center.y > tableView.bounds.height * 0.5) && (cell.center.y < (tableView.contentSize.height - tableView.bounds.height * 0.5)) { tableView.setContentOffset(CGPoint(x: 0, y: cell.frame.origin.y + cell.bounds.height * 1.0 - tableView.bounds.height * 0.5), animated: true) }else{ tableView.setContentOffset(CGPoint(x: 0, y: (tableView.contentSize.height + cell.bounds.height - tableView.bounds.size.height )), animated: true) } } } //MARK: 代理方法 -> extension SingleGiftViewController:UITableViewDataSource,UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50.0 } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 18 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: singleGiftColumnIndentifier, for: indexPath) as! SingleGiftColumnCell cell.viewModel = SingleGiftColumnCellViewModel(withModel: SingleGiftColumnCellDataModel(withIndex: indexPath.row)) cell.selectedCell(select: selectedColumnRow == indexPath.row ? true: false) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { isSelectedColumn = true selectedColumnRow = indexPath.row tableView.reloadData() //: 滚动居中 tableViewScrollToAt(indexPath:indexPath) collectionView.scrollToItem(at: IndexPath(item: 0, section: indexPath.row), at: .top, animated: true) } } extension SingleGiftViewController:UICollectionViewDelegate,UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 18 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 6 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: singleGiftIndentifier, for: indexPath) as!SingleGiftCell cell.viewModel = SingleGiftCellViewModel(withModel: SingleGiftCellDataModel()) return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let cell = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: singleGiftSectionIndentifier, for: indexPath) as! SingleGiftSectionView cell.viewModel = SingleGiftSectionViewModel(withModel: SingleGiftSectionDataModel(withIndex: indexPath.section)) updateTableViewWhenScrollCollectionView() return cell } func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isSelectedColumn = !scrollView.isKind(of: UICollectionView.self) updateTableViewWhenScrollCollectionView() } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { updateTableViewWhenScrollCollectionView() } func updateTableViewWhenScrollCollectionView() { guard let currentIndexPath = collectionView.indexPathsForVisibleItems.last else { return } if !isSelectedColumn && selectedColumnRow != currentIndexPath.section { selectedColumnRow = currentIndexPath.section tableView.reloadData() //: 滚动居中 tableViewScrollToAt(indexPath:IndexPath(row: currentIndexPath.section, section: 0)) } } } class SingleGiftViewFlowLayout:UICollectionViewFlowLayout{ override func prepare() { super.prepare() minimumLineSpacing = margin minimumInteritemSpacing = margin * 0.5 let width = (collectionView!.bounds.width - (margin * CGFloat(cellColumns + 1))) / CGFloat(cellColumns) let height = width / cellScale itemSize = CGSize(width: width, height: height) sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin) headerReferenceSize = CGSize(width: ScreenWidth, height: 44) scrollDirection = .vertical } }
mit
71899dd90331056e2f17d699d50bdbbe
35.41629
205
0.681039
5.456271
false
false
false
false
jindulys/Leetcode_Solutions_Swift
Sources/DynamicProgramming/5_LongestPalindromicSubString.swift
1
1647
// // 5_LongestPalindromicSubString.swift // LeetcodeSwift // // Created by yansong li on 2016-09-05. // Copyright © 2016 YANSONG LI. All rights reserved. // import Foundation /** * Dynamic Programmin * if s[i] == s[j], then we need to check whether or not s[i+1,..,j-1] is * palindrome. */ /** Title:5 Longest Palindromic Substring URL: https://leetcode.com/problems/longest-palindromic-substring/ Space: O(n^2) Time: O(n^2) */ class LongestPalindromicSubString_Solution { func longestPalindrome(_ s: String) -> String { guard s.characters.count > 1 else { return s } let characters = Array(s.characters) let totalLength = characters.count var maxStartIndex: Int = 0 var maxLength: Int = 1 var palindromicTable = Array(repeating: Array(repeating: false, count: totalLength), count: totalLength) for i in 0..<characters.count { palindromicTable[i][i] = true maxStartIndex = i maxLength = 1 } for i in 0..<characters.count - 1 { if characters[i] == characters[i + 1] { palindromicTable[i][i+1] = true maxLength = 2 maxStartIndex = i } } if totalLength >= 3 { for length in 3...totalLength { for i in 0...(totalLength - length) { if characters[i] == characters[i + length - 1] && palindromicTable[i + 1][i + length - 2] == true { palindromicTable[i][i + length - 1] = true maxStartIndex = i maxLength = length } } } } return String(characters[maxStartIndex...(maxStartIndex + maxLength - 1)]) } }
mit
ea5d2dee30e5853b6808ca37a55773d4
25.548387
78
0.599028
3.707207
false
false
false
false
instacart/TrueTime.swift
Sources/ReferenceTime.swift
1
1789
// // FrozenReferenceTime.swift // TrueTime // // Created by Michael Sanders on 10/26/16. // Copyright © 2016 Instacart. All rights reserved. // typealias FrozenTimeResult = Result<FrozenTime, NSError> typealias FrozenTimeCallback = (FrozenTimeResult) -> Void typealias FrozenNetworkTimeResult = Result<FrozenNetworkTime, NSError> typealias FrozenNetworkTimeCallback = (FrozenNetworkTimeResult) -> Void protocol FrozenTime { var time: Date { get } var uptime: timeval { get } } struct FrozenReferenceTime: FrozenTime { let time: Date let uptime: timeval } struct FrozenNetworkTime: FrozenTime { let time: Date let uptime: timeval let serverResponse: NTPResponse let startTime: ntp_time_t let sampleSize: Int? let host: String? init(time: Date, uptime: timeval, serverResponse: NTPResponse, startTime: ntp_time_t, sampleSize: Int? = 0, host: String? = nil) { self.time = time self.uptime = uptime self.serverResponse = serverResponse self.startTime = startTime self.sampleSize = sampleSize self.host = host } init(networkTime time: FrozenNetworkTime, sampleSize: Int, host: String) { self.init(time: time.time, uptime: time.uptime, serverResponse: time.serverResponse, startTime: time.startTime, sampleSize: sampleSize, host: host) } } extension FrozenTime { var uptimeInterval: TimeInterval { let currentUptime = timeval.uptime() return TimeInterval(milliseconds: currentUptime.milliseconds - uptime.milliseconds) } func now() -> Date { return time.addingTimeInterval(uptimeInterval) } }
apache-2.0
0054571ca7623b64eeb30b7e0b607560
26.090909
91
0.649888
4.15814
false
false
false
false
ThunderStruct/MSCircularSlider
MSCircularSliderExample/MSCircularSliderExample/MarkersLabelsVC.swift
1
3641
// // MarkersLabelsVC.swift // MSCircularSliderExample // // Created by Mohamed Shahawy on 10/2/17. // Copyright © 2017 Mohamed Shahawy. All rights reserved. // import UIKit class MarkersLabelsVC: UIViewController, MSCircularSliderDelegate, ColorPickerDelegate { // Outlets @IBOutlet weak var sliderView: UIView! // frame reference @IBOutlet weak var markerCountLbl: UILabel! @IBOutlet weak var labelsColorBtn: UIButton! @IBOutlet weak var markersColorBtn: UIButton! @IBOutlet weak var valueLbl: UILabel! @IBOutlet weak var snapToLabelSwitch: UISwitch! @IBOutlet weak var snapToMarkerSwitch: UISwitch! // Members var slider: MSCircularSlider? var currentColorPickTag = 0 var colorPicker: ColorPickerView? // Actions @IBAction func labelsTextfieldDidChange(_ sender: UITextField) { let text = sender.text! if !text.trimmingCharacters(in: .whitespaces).isEmpty { slider?.labels = text.components(separatedBy: ",") } else { slider?.labels.removeAll() } } @IBAction func markerCountStepperValueChanged(_ sender: UIStepper) { slider?.markerCount = Int(sender.value) markerCountLbl.text = "\(slider?.markerCount ?? 0) Marker\(slider?.markerCount == 1 ? "": "s")" } @IBAction func colorPickAction(_ sender: UIButton) { currentColorPickTag = sender.tag colorPicker?.isHidden = false } @IBAction func snapToLabelsValueChanged(_ sender: UISwitch) { slider?.snapToLabels = sender.isOn //snapToMarkerSwitch.setOn(false, animated: true) // mutually-exclusive } @IBAction func snapToMarkersValueChanged(_ sender: UISwitch) { slider?.snapToMarkers = sender.isOn //snapToLabelSwitch.setOn(false, animated: true) // mutually-exclusive } // Init override func viewDidLoad() { super.viewDidLoad() // Slider programmatic instantiation slider = MSCircularSlider(frame: sliderView.frame) slider?.delegate = self view.addSubview(slider!) colorPicker = ColorPickerView(frame: CGRect(x: 0, y: view.center.y - view.frame.height * 0.3 / 2.0, width: view.frame.width, height: view.frame.height * 0.3)) colorPicker?.isHidden = true colorPicker?.delegate = self view.addSubview(colorPicker!) valueLbl.text = String(format: "%.1f", (slider?.currentValue)!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Delegate Methods func circularSlider(_ slider: MSCircularSlider, valueChangedTo value: Double, fromUser: Bool) { valueLbl.text = String(format: "%.1f", value) } func circularSlider(_ slider: MSCircularSlider, startedTrackingWith value: Double) { // optional delegate method } func circularSlider(_ slider: MSCircularSlider, endedTrackingWith value: Double) { // optional delegate method } func colorPickerTouched(sender: ColorPickerView, color: UIColor, point: CGPoint, state: UIGestureRecognizer.State) { switch currentColorPickTag { case 0: labelsColorBtn.setTitleColor(color, for: .normal) slider?.labelColor = color case 1: markersColorBtn.setTitleColor(color, for: .normal) slider?.markerColor = color default: break } colorPicker?.isHidden = true } }
mit
f7e937379bcf3a21b100ee555d1ecc45
31.792793
166
0.643132
4.636943
false
false
false
false
customerly/Customerly-iOS-SDK
CustomerlySDK/Library/View Controllers/CySurveyListViewController.swift
1
1998
// // CySurveyListViewController.swift // Customerly // // Created by Paolo Musolino on 01/01/17. // Copyright © 2017 Customerly. All rights reserved. // import UIKit class CySurveyListViewController: CyViewController { @IBOutlet weak var tableView: CyTableView! @IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint! var returnClosure: SurveyParamsReturn? var choices: [CySurveyChoiceResponseModel] = [] var showRadioButtons = false override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func selectedChoice(datas: CySurveyParamsRequestModel? = nil, params:SurveyParamsReturn? = nil){ self.returnClosure = params } } extension CySurveyListViewController: UITableViewDelegate{ func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let surveyParams = CySurveyParamsRequestModel(JSON: [:]) surveyParams?.survey_id = choices[indexPath.row].survey_id surveyParams?.choice_id = choices[indexPath.row].choice_id surveyParams?.token = CyStorage.getCyDataModel()?.token self.returnClosure?(surveyParams) } } extension CySurveyListViewController: UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return choices.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: (showRadioButtons == false ? "surveyButtonCell" : "radioButtonCell"), for: indexPath) as! CySurveyButtonTableViewCell cell.button.setTitle(choices[indexPath.row].value, for: .normal) tableViewHeightConstraint.constant = tableView.contentSize.height return cell } }
apache-2.0
ca24dca260a19ade482e87887684a486
33.431034
182
0.710065
4.955335
false
false
false
false
OlegNovosad/Severenity
iOS/Severenity/Views/MapViewController.swift
2
5784
// // Tab3ViewController.swift // severenityProject // // Created by Yura Yasinskyy on 12.09.16. // Copyright © 2016 severenity. All rights reserved. // import UIKit import GoogleMaps class MapViewController: UIViewController { internal var presenter: MapPresenter? internal var markers: [String: GMSMarker] = [:] let locationManager = CLLocationManager() @IBOutlet var mapView: GMSMapView! // MARK: Init required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) presenter = MapPresenter() presenter?.delegate = self Log.info(message: "Map VIPER module init did complete", sender: self) } // MARK: Loading view override func viewDidLoad() { super.viewDidLoad() Log.info(message: "Map tab did load", sender: self) locationManager.requestWhenInUseAuthorization() if CLLocationManager.locationServicesEnabled() { locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.startUpdatingLocation() } if CLLocationManager.authorizationStatus() == .denied { let locationAlertController = UIAlertController(title: "Hello dear user!", message: kNeedsLocationServicesAccess, preferredStyle: .alert) let defaultAction = UIAlertAction.init(title: "Ok", style: .default, handler: { (action) in exit(0) }) locationAlertController.addAction(defaultAction) present(locationAlertController, animated: true, completion: nil) } else { mapView.delegate = self view = mapView mapView.isMyLocationEnabled = false if let currentLatitude = locationManager.location?.coordinate.latitude, let currentLongitude = locationManager.location?.coordinate.longitude { mapView.moveCamera(GMSCameraUpdate.setCamera(GMSCameraPosition.camera(withLatitude: currentLatitude, longitude: currentLongitude, zoom: 4))) } } } /**- Calling this method simply adjust GoogleMap to see all markers */ internal func showAllMarkersOnMap() { guard let firstPlace = markers.first?.value.position else { Log.error(message: "Cannot zoom map to see all markers", sender: self) return } var bounds = GMSCoordinateBounds.init(coordinate: firstPlace, coordinate: firstPlace) for marker in markers { bounds = bounds.includingCoordinate(marker.value.position) } mapView.animate(with: GMSCameraUpdate.fit(bounds, with: UIEdgeInsetsMake(50, 50, 50, 50))) } } // MARK: MapPresenter delegate extension MapViewController: MapPresenterDelegate { func addNewPlaceToMap(with data: Dictionary<String,Any>) { Log.info(message: "MapPresenter did call MapViewController with data: \(data)", sender: self) let marker = GMSMarker() if let lat = data["lat"] as? Double, let lng = data["lng"] as? Double { marker.position = CLLocationCoordinate2DMake(lat, lng) } marker.title = data["name"] as? String marker.map = mapView if let placeId = data["placeId"] as? String { markers[placeId] = marker } Log.info(message: "New place marker added to the map", sender: self) tabBarController?.selectedIndex = 2 showAllMarkersOnMap() } func addNewPlayerToMap(with image: UIImage, and coordinates: CLLocationCoordinate2D, and info: Dictionary<String,String>) { guard let userID = info["id"], let userName = info["name"] else { Log.error(message: "Cannot add player marker to map with recieved info", sender: self) return } var customImage = image.roundedImageWithBorder(with: 5, and: #colorLiteral(red: 0.5176470588, green: 0.3411764706, blue: 0.6, alpha: 1)) customImage = customImage?.imageResize(sizeChange: CGSize.init(width: 45, height: 45)) if markers[userID] != nil { markers[userID]?.icon = customImage markers[userID]?.position = coordinates markers[userID]?.title = userName Log.info(message: "Recieved player marker is already on the map. Coordinates were updated.", sender: self) } else { let marker = GMSMarker() marker.position = coordinates marker.title = userName marker.icon = customImage marker.map = mapView markers[userID] = marker Log.info(message: "New player marker added to the map", sender: self) } } } // MARK: GMSMapViewDelegate extension MapViewController: GMSMapViewDelegate { func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { mapView.moveCamera(GMSCameraUpdate.setCamera(GMSCameraPosition.camera(withLatitude: marker.position.latitude, longitude: marker.position.longitude, zoom: 18))) mapView.selectedMarker = marker return true } } // MARK: CLLocationManager delegate extension MapViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let currentLocation = locations.first { presenter?.userLocationUpdate(currentLocation) } } }
apache-2.0
09ff21b825c1a0beffede02a803e697a
39.440559
155
0.61577
5.205221
false
false
false
false