Difference between revisions of "Swift code snippets"

From Hawk Wiki
Jump to: navigation, search
(Swift use NSUserDefaults to store persistence data)
 
(9 intermediate revisions by the same user not shown)
Line 1: Line 1:
=Swift Code snippts=
+
=Swift Code Snippts=
 
Back To [[IOS_Swift]]
 
Back To [[IOS_Swift]]
 
==[[Swift: Use NSUserDefaults to Store Persistence Data]]==
 
==[[Swift: Use NSUserDefaults to Store Persistence Data]]==
  
==Making Network Request==
+
==[[Swift: Making Network Request Using NSURLConnection]]==
<pre class="brush:swift">
+
var clientId = "Put your client id here"
+
+
var url = NSURL(string: "https://api.instagram.com/v1/media/popular?client_id=\(clientId)")!
+
var request = NSURLRequest(URL: url)
+
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
+
    var responseDictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as NSDictionary
+
    self.photos = responseDictionary["data"] as NSArray
+
    self.tableView.reloadData()
+
   
+
    println("response: \(self.photos)")
+
}
+
</pre>
+
  
==Use AFNetworking setImageWithURL==
+
==[[Swift:Use AFNetworking setImageWithURL]]==
Create the bridging file: create a new Objective-C file, name it anything, and when you save it, Xcode will prompt you generate a bridging file. <br>
+
In an Objective-C bridging file:
+
<pre class="brush:swift">
+
#import <AFNetworking/UIImageView+AFNetworking.h>
+
</pre>
+
In the swift view file, to set a imageView using URL:
+
<pre class="brush:swift">
+
setImageWithURL(NSURL(string: thumbnailURL))
+
</pre>
+
  
==Adding UIRefreshControl==
+
==[[Swift:Using UIRefreshControl]]==
<pre class="brush:swift">
+
//refreshControl is automatically defined in UITableViewController
+
var refreshControl: UIRefreshControl?
+
override func viewDidLoad() {
+
    super.viewDidLoad()
+
   
+
    refreshControl = UIRefreshControl()
+
    refreshControl?.addTarget(self, action: "fetch", forControlEvents: UIControlEvents.ValueChanged)
+
    tableView.insertSubview(refreshControl!, atIndex: 0)
+
}
+
  
//to stop refresh, call
+
==[[Swift:Using UIGestureRecognizer]]==
if let rc = self.refreshControl {
+
    self.refreshControl!.endRefreshing()
+
}
+
</pre>
+
  
==Example of fetching messages from Parse==
+
==Swift:Example of fetching messages from Parse==
 
https://gist.github.com/sandofsky/7134b1ff90d235901254
 
https://gist.github.com/sandofsky/7134b1ff90d235901254
==Auto Table Row Height==
 
<pre class="brush:swift">
 
//Auto table row height
 
tableView.estimatedRowHeight = 92.0
 
tableView.rowHeight = UITableViewAutomaticDimension
 
</pre>
 
==Navigation between storyboards==
 
===Navigate to Storyboard ID===
 
<pre class="brush:swift">
 
var vc = storyboard.instantiateViewControllerWithIdentifier("loginViewController") as UIViewController
 
window?.rootViewController = vc
 
</pre>
 
===Navigate Segue by Identifier===
 
First, drag a segue in storyboard and give it an identifier, then in the button action (or any action you like), do:
 
<pre class="brush:swift">
 
self.performSegueWithIdentifier("loginSegue", sender: self)
 
</pre>
 
===Get UIVewController from Navigation Controller===
 
Sometimes, you want to access the UIViewController from a navigation controller
 
<pre class="brush:swift">
 
var vc = storyboard?.instantiateViewControllerWithIdentifier("navigationID") as UINavigationController
 
var v = vc.viewControllers[0] as ViewController // [0] represents the first level UIViewController under NavigationController
 
</pre>
 
==Notification in Swift==
 
Listen notification in swift
 
<pre class="brush:swift">
 
func tweetSent(notification: NSNotification) {
 
    let newTweet:Dictionary<String, Tweet> = notification.userInfo as Dictionary<String, Tweet>
 
}
 
NSNotificationCenter.defaultCenter().addObserver(self, selector: "tweetSent:", name: "newTweetNotification", object: nil)
 
</pre>
 
Send/Post notification in swift
 
<pre class="brush:swift">
 
var userInfo: Dictionary<String, Tweet> = ["tweet": newTweet]
 
NSNotificationCenter.defaultCenter().postNotificationName("newTweetNotification", object: nil, userInfo: userInfo)
 
</pre>
 
Remove notification observer
 
<pre class="brush:swift">
 
deinit {
 
    NSNotificationCenter.defaultCenter().removeObserver(self)
 
}
 
</pre>
 
==Get Raw Histogram from CGImage in swift==
 
Credit to http://stackoverflow.com/questions/27237297/how-to-get-meaningful-ciareahistogram-output
 
  
<pre class="brush:swift">
+
==[[Swift:Auto Table Row Height]]==
//dataImage is a CGImage
+
var imageData: CFDataRef = CGDataProviderCopyData(CGImageGetDataProvider(dataImage))
+
var dataInput: UnsafePointer<UInt8> = CFDataGetBytePtr(imageData)
+
//In swift, I have to do 2 steps. Not sure if there is any better way
+
var dataInputMutable = UnsafeMutablePointer<Void>(dataInput)
+
var height: vImagePixelCount = CGImageGetHeight(dataImage)
+
var width: vImagePixelCount = CGImageGetWidth(dataImage)
+
//Build a vImage_Buffer for next step
+
var vImageBuffer = vImage_Buffer(data: dataInputMutable, height: height, width: width, rowBytes: CGImageGetBytesPerRow(dataImage))
+
//Build the output array.
+
//To init a multi-dimensional UnsafeMutablePointer array. I have to do 3 steps
+
//First alloc sub arrays
+
var r = UnsafeMutablePointer<vImagePixelCount>.alloc(256)
+
var g = UnsafeMutablePointer<vImagePixelCount>.alloc(256)
+
var b = UnsafeMutablePointer<vImagePixelCount>.alloc(256)
+
var a = UnsafeMutablePointer<vImagePixelCount>.alloc(256)
+
//Then alloc main array
+
var histogram = UnsafeMutablePointer<UnsafeMutablePointer<vImagePixelCount>>.alloc(4)
+
//Set the pointer of sub arrays
+
histogram[0] = r
+
histogram[1] = g
+
histogram[2] = b
+
histogram[3] = a
+
//Finally, do the histogram calculation
+
var error:vImage_Error = vImageHistogramCalculation_ARGB8888(&vImageBuffer, histogram, 0);
+
       
+
if (error == kvImageNoError) {
+
    for var j = 0; j < 256; j++ {
+
        let currentVal = histogram[0][j] + histogram[1][j] + histogram[2][j] //I am making a grey histogram
+
        if currentVal > 0 {
+
            println("j=\(j),\(currentVal)")
+
        }
+
    }
+
    //delloc. MUST do this manually to prevent memory leak
+
    r.dealloc(256)
+
    g.dealloc(256)
+
    b.dealloc(256)
+
    a.dealloc(256)
+
    histogram.dealloc(4)
+
} else {
+
    println("Histogram vImage error: \(error)")
+
}
+
</pre>
+
==Xcode Swift Create Custom UIColor==
+
<pre class="brush:swift">let swiftColor = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1)</pre>
+
  
==UIGraphics Drawing on UIView==
+
==[[Swift:Navigation between storyboards]]==
===Swift: Tutorial Drawing Graphic===
+
See http://www.techotopia.com/index.php/An_iOS_8_Swift_Graphics_Tutorial_using_Core_Graphics_and_Core_Image
+
  
===Swift: How to make UIGraphics context background transparent===
+
==[[Swift:Notification Observer Using NSNotificationCenter]]==
If you want to set a transparent background of the content you are drawing.
+
<pre class="brush:swift">
+
// UIGraphics draw transparent background context
+
@IBOutlet weak var histogramView: HistogramView!
+
override func viewWillAppear(animated: Bool) {
+
    histogramView.opaque = false
+
    histogramView.backgroundColor = UIColor.clearColor()
+
}
+
class HistogramView: UIView {
+
    override func drawRect(rect: CGRect) {
+
        // draw content
+
        let context = UIGraphicsGetCurrentContext()
+
        CGContextClearRect(context, rect)
+
    }
+
}
+
</pre>
+
  
==Swift: Scale down CGImage==
+
==[[Swift:Get Raw Histogram from CGImage]]==
<pre class="brush:swift">
+
func scaleDownCGImage(image: CGImage, scale: Float) -> CGImage!{
+
    var scaleDiv = UInt(1.0 / scale)
+
    let width = CGImageGetWidth(image) / scaleDiv
+
    let height = CGImageGetHeight(image) / scaleDiv
+
    let bitsPerComponent = CGImageGetBitsPerComponent(image)
+
    let bytesPerRow = CGImageGetBytesPerRow(image)
+
    let colorSpace = CGImageGetColorSpace(image)
+
    let bitmapInfo = CGImageGetBitmapInfo(image)
+
    let context = CGBitmapContextCreate(nil, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)
+
    CGContextSetInterpolationQuality(context, kCGInterpolationMedium)
+
    let imgSize = CGSize(width: Int(width), height: Int(height))
+
    CGContextDrawImage(context, CGRect(origin: CGPointZero, size: imgSize), image)
+
    return CGBitmapContextCreateImage(context)
+
}
+
</pre>
+
  
 +
==[[Swift:UIGraphics Drawing on UIView]]==
  
==Swift: Convert between CGImage, CIImage and UIImage==
+
==[[Swift:UIGraphics Scale Down CGImage]]==
===Swift: Convert CIImage to CGImage===
+
<pre class="brush:swift">
+
func convertCIImageToCGImage(inputImage: CIImage) -> CGImage! {
+
    let context = CIContext(options: nil)
+
    if context != nil {
+
        return context.createCGImage(inputImage, fromRect: inputImage.extent())
+
    }
+
    return nil
+
}
+
</pre>
+
===Swift: Convert CGImage to CIImage===
+
<pre class="brush:swift">
+
func convertCGImageToCIImage(inputImage: CGImage) -> CIImage! {
+
  var ciImage = CIImage(CGImage: inputImage)
+
    return ciImage
+
}
+
</pre>
+
===Swift: Convert CGImage or CIImage to UIImage===
+
<pre class="brush:swift">
+
UIImage(CGImage: cgImage)
+
UIImage(CIImage: ciImage)
+
</pre>
+
===Swift: Convert UIImage to CIImage===
+
<pre class="brush:swift">
+
//uiImage: UIImage
+
//Convert to CIImage
+
var ciImage = CIImage(image: uiImage)
+
</pre>
+
===Swift: Convert UIImage to CGImage===
+
To convert to CGImage, it requires 2 steps:
+
  
First convert to CIImage [[#Swift: Convert UIImage to CIImage]].
+
==[[Swift: Convert between CGImage, CIImage and UIImage]]==
  
Then convert to CGImage [[#Swift:_Convert_CIImage_to_CGImage]]
+
==[[Swift:Detect Volumn Button Press]]==
  
==Swift Detect Volumn Button Press==
+
==[[Swift:NSTimer scheduledTimerWithTimeInterval]]==
Credit to http://stackoverflow.com/questions/28471481/swift-detect-volume-button-press
+
 
+
Detect volume button press, also hide volume HUD
+
 
+
<pre class="brush:swift">
+
import MediaPlayer //Only for hidding  Volume view
+
func listenVolumeButton(){
+
 
+
    let audioSession = AVAudioSession.sharedInstance()
+
    audioSession.setActive(true, error: nil)
+
    audioSession.addObserver(self, forKeyPath: "outputVolume", options: NSKeyValueObservingOptions.New, context: nil)
+
    //If you want to hide Volume HUD view
+
    var volumeView: MPVolumeView = MPVolumeView(frame: CGRectZero)
+
    view.addSubview(volumeView)
+
}
+
 
+
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject,
+
    change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
+
    if keyPath == "outputVolume"{
+
        print("got in here")
+
    }
+
}
+
 
+
</pre>
+

Latest revision as of 03:10, 9 April 2015

Swift Code Snippts

Back To IOS_Swift

Swift: Use NSUserDefaults to Store Persistence Data

Swift: Making Network Request Using NSURLConnection

Swift:Use AFNetworking setImageWithURL

Swift:Using UIRefreshControl

Swift:Using UIGestureRecognizer

Swift:Example of fetching messages from Parse

https://gist.github.com/sandofsky/7134b1ff90d235901254

Swift:Auto Table Row Height

Swift:Navigation between storyboards

Swift:Notification Observer Using NSNotificationCenter

Swift:Get Raw Histogram from CGImage

Swift:UIGraphics Drawing on UIView

Swift:UIGraphics Scale Down CGImage

Swift: Convert between CGImage, CIImage and UIImage

Swift:Detect Volumn Button Press

Swift:NSTimer scheduledTimerWithTimeInterval