working on it ...

Filters

Explore Public Snippets

Sort by

Found 129 snippets matching: swift2

    public by marksimon232  283249  0  7  1

    Swift 2: Custom logger that mimics NSLog

    Using this initializer, you can easily build a custom logger that mimics NSLog:
    public func SWLog(format: String, _ args: CVarArgType...) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = 
            NSDateFormatter.dateFormatFromTemplate(
                "mm:ss:SSS", options: 0, 
                locale: NSLocale.currentLocale())
        let timeString = 
            dateFormatter.stringFromDate(NSDate())
        print("\(timeString): " + 
            String(format: format, arguments: args))
    }

    public by marksimon232  3608  0  6  0

    Swift2: DebugPrint differentiation

    Find items that printed differently in debugPrint than they did in print.
    import Cocoa
    
    // Items to check
    //let x = "Snoop"
    //let x = 1...5
    let x = UnicodeScalar(0x1f601)
    
    // Build test cases
    var a = ""; print(x, &a, appendNewline:false); print(a)
    var b = ""; debugPrint(x, &b, appendNewline:false); print(b)
    
    // Compare and alert
    func ExitAfter(t: Double, _ status: Int32) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 
            numericCast(UInt64(t * Double(NSEC_PER_SEC)))), 
            dispatch_get_global_queue(
                DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), 
            {exit(status)})
    }
    
    if a != b {
        // Success
        print("YES!")
        NSSound(named: "Sosumi")?.play()
        ExitAfter(0.5, 0)
        CFRunLoopRun() // stick around to produce sound
    } else {print("No")}

    public by marksimon232  4523  2  6  1

    Swift 2: Creating the date Formatter

    internal func BuildSimpleTimeFormatter() -> NSDateFormatter {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("mm:ss:SSS", options: 0, locale: NSLocale.currentLocale())
        return dateFormatter
    }
    
    internal let dateFormatter = BuildSimpleTimeFormatter()
    
    public func SWLog(format: String, _ args: CVarArgType...) {
        #if DEBUG
            let timeString = dateFormatter.stringFromDate(NSDate())
            print("\(timeString): " + String(format: format, arguments: args), &errStream)
        #endif
    }

    public by marksimon232  3547  2  6  0

    Swift: .max and .min properties

    If you have code around that uses lots of F’s (e.g. 0xFFFFFFFF) or capital letters (e.g. UINT32_MAX), consider replacing these constants with built-in Swift versions.
    Swift offers .max and .min properties for many numeric types. For example:
    
    public func Random01() -> Double {
        return Double(arc4random()) / Double(UInt32.max)
    }

    public by marksimon232  2963  0  7  1

    Swift: Revisiting printing with string formats

    You pass NSLog a format string followed by a variadic list of Objective-C-compatible parameters. 
    The parameters map to specifiers embedded within the format string.
    
    NSLog("Dictionary: %@, Double: %0.2f", ["Hello":3], 2.7)            

    external by enix223  68  0  1  0

    Calculate SHA1 with Swift2

    Calculate SHA1 with Swift2: swift2-calculate-sha1.swift
    //
    //  TestSHA1Digest.swift
    //  SwiftPlayground
    //
    //  Created by Enix Yu on 31/10/2016.
    //  Copyright © 2016 RobotBros. All rights reserved.
    //
    //  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    //  !!     Be sure to #import <CommonCrypto/CommonCrypto.h> in the bridging header file     !!
    //  !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    //
    
    import UIKit
    
    extension String {
        func sha1() -> String {
            let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
            var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
            CC_SHA1(data.bytes, CC_LONG(data.length), &digest)
            let hexBytes = digest.map { String(format: "%02hhx", $0) }
            return hexBytes.joinWithSeparator("")
        }
        
        func sha1Data() -> NSData {
            let data = self.dataUsingEncoding(NSUTF8StringEncoding)!
            var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0)
            CC_SHA1(data.bytes, CC_LONG(data.length), &digest)
            let digestData = NSData(bytes: digest, length: digest.count)
            return digestData
        }
    }
    
    /* 
    Swift 3
     
    extension String {
        func sha1() -> String {
            let data = self.data(using: String.Encoding.utf8)!
            var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
            data.withUnsafeBytes {
                _ = CC_SHA1($0, CC_LONG(data.count), &digest)
            }
            let hexBytes = digest.map { String(format: "%02hhx", $0) }
            return hexBytes.joined()
        }
    }
    */
    
    
    class TestSHA1Digest: UIViewController {
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            if let b64 = calculateDigest("2.045020311114033331503343429780020454510MDAwMDAwMDAwMDAwMDA2ODkzOTI=https://myeshop.gr/orders/Payment_Okhttps://myeshop.gr/orders/Payment_FailEURO123") {
                print("SHA1: \(b64)")
            } else {
                print("Calcuate SHA1 failed")
            }
        }
        
        func calculateDigest(data: String) -> String? {
            let shaData = data.sha1Data()
            return shaData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
        }
    }
    
    

    external by CodeYourDay  57  0  1  0

    Hide keyboard -code for entire app, Swift2

    Hide keyboard -code for entire app, Swift2: HidingKeyboard
    //Keyboard
    extension UIViewController {
        func hideKeyboardWhenTappedAround() {
            let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
            view.addGestureRecognizer(tap)
        }
        
        func dismissKeyboard() {
            view.endEditing(true)
        }
    }
    
    

    external by Josh Friend  45  0  1  0

    Semaphore wrapper for swift2

    Semaphore wrapper for swift2: Semaphore.swift
    import Foundation
    
    
    struct Semaphore {
        typealias Signal = () -> Int
    
        private let semaphore: dispatch_semaphore_t
    
        init(count: Int = 0) {
            self.semaphore = dispatch_semaphore_create(count)
        }
    
        func signal() -> Int {
            return dispatch_semaphore_signal(self.semaphore)
        }
    
        func wait(until timeout: UInt64) -> Int {
            return dispatch_semaphore_wait(self.semaphore, timeout: timeout)
        }
    
        func waitForever() -> Int {
            return self.wait(until: DISPATCH_TIME_FOREVER)
        }
    
        func wait(until timeout: UInt64, forBlock block: (Signal) -> Void) {
            let done: Signal = {
                return self.signal()
            }
    
            block(done)
            return self.wait(until: timeout)
        }
    
        func waitForever(forBlock block: (Signal) -> Void) {
            return self.wait(until: DISPATCH_TIME_FOREVER, forBlock: block)
        }
    }
    
    
    

    external by Tadatoshi Hanazaki  1209  0  3  0

    Swift2 で AVCaptureStillImageOutput を使ったカメラ撮影

    Swift2 で AVCaptureStillImageOutput を使ったカメラ撮影: CameraViewController.swift
    //
    //  CameraViewController.swift
    //
    //  Created by Tadatoshi Hanazaki on 2016/01/17.
    //  Copyright © 2016年 close-to.biz. All rights reserved.
    //
    
    import UIKit
    import AVFoundation
    
    class CameraViewController: UIViewController, UIGestureRecognizerDelegate {
    
        // AVキャプチャセッション
        var avSession: AVCaptureSession!
    
        // AVキャプチャデバイス
        var avDevice: AVCaptureDevice!
    
        // AVキャプチャデバイスインプット
        var avInput: AVCaptureInput!
    
        // AVキャプチャアウトプット
        var avOutput: AVCaptureStillImageOutput!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // 画面タップで撮影
            let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "takePhoto:")
            tapGesture.delegate = self;
            self.view.addGestureRecognizer(tapGesture)
            
        }
    
        override func viewWillAppear(animated: Bool) {
            super.viewWillAppear(animated)
            self.initCamera()
        }
    
        func initCamera() {
            
            // AVキャプチャセッション
            // (AVFoundationにおけるキャプチャ入出力を管理するクラス)
            avSession = AVCaptureSession()
    
            if (avSession.canSetSessionPreset(AVCaptureSessionPresetPhoto)) {
                avSession.beginConfiguration()
    
                // キャプチャクオリティ設定
                // AVCaptureSessionPresetPhoto    写真専用最大解像度
                // AVCaptureSessionPresetHigh     最高録画品質
                // AVCaptureSessionPresetMedium   WiFi向け
                // AVCaptureSessionPresetLow      3G向け
                // AVCaptureSessionPreset640x480  640x480 VGA固定
                // AVCaptureSessionPreset1280x720 1280x720 HD固定
                avSession.sessionPreset = AVCaptureSessionPresetPhoto
    
                avSession.commitConfiguration()
            }
            
            // AVキャプチャデバイス
            // (前背面カメラやマイク等のデバイス)
            let devices = AVCaptureDevice.devices()
            for capDevice in devices {
                if (capDevice.position == AVCaptureDevicePosition.Back) {
                    // 背面カメラを取得
                    avDevice = capDevice as? AVCaptureDevice
                }
            }
    
            if (avDevice != nil) {
    
                // AVキャプチャデバイスインプット
                // (AVキャプチャデバイスからの入力)
                do {
                    // バックカメラからVideoInputを取得
                    avInput = try AVCaptureDeviceInput.init(device: avDevice!)
                } catch let error as NSError {
                    print(error)
                }
    
                // AVキャプチャデバイスインプットをセッションに追加
                if (avSession.canAddInput(avInput)) {
    
                    avSession.addInput(avInput)
    
                    // AVキャプチャアウトプット (出力方法)
                    // AVCaptureStillImageOutput: 静止画
                    // AVCaptureMovieFileOutput: 動画ファイル
                    // AVCaptureAudioFileOutput: 音声ファイル
                    // AVCaptureVideoDataOutput: 動画フレームデータ
                    // AVCaptureAudioDataOutput: 音声データ
    
                    avOutput = AVCaptureStillImageOutput()
    
                    // 出力設定
                    avOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
    
                    // AVキャプチャアウトプットをセッションに追加
                    if (avSession.canAddOutput(avOutput)) {
                        avSession.addOutput(avOutput)
                    }
    
                    // 画像を表示するレイヤーを生成.
                    let capVideoLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer.init(session:avSession)
                    capVideoLayer.frame = self.view.bounds
                    capVideoLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    
                    // AVLayerVideoGravityResizeAspectFill
                    //      アスペクト比維持 + 必要に応じてトリミング (縦いっぱいに表示し横をトリミング)
    
                    // AVLayerVideoGravityResizeAspect
                    //      アスペクト比維持 (縦横とも収まる様に表示)
    
                    // AVLayerVideoGravityResize
                    //      利用可能な画面領域いっぱいにリサイズ
    
    
                    // Viewに追加.
                    self.view.layer.addSublayer(capVideoLayer)
    
                    // セッション開始.
                    avSession.startRunning()
    
                    renderView()
    
                }
    
            } else {
    
                // UIAlertControllerを作成する.
                let sampleAlert: UIAlertController = UIAlertController(title: "", message: "背面カメラがある実機で動かしてね。", preferredStyle: .Alert)
                
                // アクションを作成、追加
                let yesAction = UIAlertAction(title: "OK", style: .Default) {
                    UIAlertAction in
                    self.close()
                }
                sampleAlert.addAction(yesAction)
                
                // UIAlertを表示する
                self.presentViewController(sampleAlert, animated: true, completion: nil)
            }
        }
    
        // 画面を閉じる
        func close() {
            self.navigationController?.popViewControllerAnimated(true)
        }
    
        // 画面になにか表示する
        func renderView() {
    
            // 角丸なLabelを作成
            let labelHello: UILabel = UILabel(frame: CGRectMake(0, 0, self.view.frame.size.width - 40, 40))
            labelHello.layer.masksToBounds = true
            labelHello.layer.cornerRadius = 5.0
    
            labelHello.lineBreakMode = NSLineBreakMode.ByCharWrapping
            labelHello.numberOfLines = 1
            
            // 文字と文字色、背景色をセット
            labelHello.text = "画面タップで撮影&アルバム保存"
            labelHello.textColor = UIColor.whiteColor()
            labelHello.backgroundColor = UIColor.init(colorLiteralRed: 0.8, green: 0.2, blue: 0.3, alpha: 1.0)
            
            // 文字を中央寄せ、ウィンドウ中央に配置
            labelHello.textAlignment = NSTextAlignment.Center
            labelHello.layer.position = CGPoint(x: self.view.bounds.width/2, y: self.view.bounds.height - 80)
    
            //tagを設定
            labelHello.tag = 100;
            //デフォルトはNOになっている。YESにする事で、タッチイベントが発生。
            labelHello.userInteractionEnabled = true;
            
            // ViewにLabelを追加.
            self.view.addSubview(labelHello)
        }
    
    
        // 撮影をする
        func takePhoto(sender: UITapGestureRecognizer){
    
            // ビデオ出力に接続する
            let videoConnection = avOutput.connectionWithMediaType(AVMediaTypeVideo)
            
            // 接続から画像を取得する
            self.avOutput.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: { (imageDataBuffer, error) -> Void in
                
                // Jpegに変換する
                let imageData: NSData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataBuffer)
                
                // UIIMageを作成する
                let image: UIImage = UIImage(data: imageData)!
                
                // アルバムに追加する
                UIImageWriteToSavedPhotosAlbum(image, self, nil, nil)
    
                self.close()
            })  
        }   
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
        }
        
    }
    
    

    external by Mark Aron Szulyovszky  1002  0  4  0

    Use NSHashTable with for .. in .. style enumeration with Swift2 (safely)

    Use NSHashTable with for .. in .. style enumeration with Swift2 (safely): NSHashTable+SequenceType.swift
    extension NSHashTable: SequenceType {
      
      public func generate() -> AnyGenerator<AnyObject> {
        
        var array = self.allObjects
        var nextIndex = array.count-1
        
        return anyGenerator {
          if (nextIndex < 0) {
            return nil
          }
          return array[nextIndex--]
        }
      }
    }
    
    
    • Public Snippets
    • Channels Snippets