TimesToCome Mobile

iOS apps and tips, tricks and tools for smart phones

Swift data to C pointer and back again




I’ve been converting my hardware sensor app from ObjC to Swift. Today I converted the sound which was easier than expected till I had to de-reference the data pointer. Hours later I have it working.

Here are the basics for converting back and forth from C pointers and Swift

let data:UInt8 = 42 // Swift 8bit int
let ps = UnsafeMutablePointer.alloc(1) // alloc one memory location
ps.initialize(data) // put the data in the memory location

let dataOut = UnsafeMutablePointer(ps) // cast the C pointer to Swift pointer
let original:UInt8 = ps.memory // grab the data and cast it to a Swift Int8

// ———— for sound capture ———————————————–

func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {

let formatDescriptionRef = CMSampleBufferGetFormatDescription(sampleBuffer)
let formatDescription = CMAudioFormatDescriptionGetStreamBasicDescription(formatDescriptionRef)

var totalBytes = 0 as UInt64

let blockBufferRef = CMSampleBufferGetDataBuffer(sampleBuffer)
var lengthOfBlock = CMBlockBufferGetDataLength(blockBufferRef)

var data = NSMutableData(length: Int(lengthOfBlock))
CMBlockBufferCopyDataBytes(blockBufferRef, 0, lengthOfBlock, data.mutableBytes)

var samples = UnsafeMutablePointer(data.mutableBytes)
var value:UInt8 = samples.memory

}


Rotating and Bouncing Sphere in SCNSceneKit and Swift




I started digging into SceneKit today, it’s very much like GLUT, for any of you old enough to remember GLUT. Source code below.

iOS Simulator Screen Shot Jul 24, 2014, 12.24.31 PMiOS Simulator Screen Shot Jul 25, 2014, 11.59.46 AM

Many thanks to Lights, Camera, Action – 3D in iOS 8 with Scene Kit who gave me enough information to get going.

Rotating Sphere source code, iOS, SceneKit, Swift
3D bouncing ball source code, iOS, SceneKit, Swift


Space Invaders in Swift




The second game I cloned to learn Swift was Space Invaders. It’s pretty close to the original. Good enough for learning more about Swift and Sprite kit.

space_invaders

Space Invaders clone source code


Mine Sweeper in Swift




I’m spending the summer learning both Swift and SpriteKit. Here is a rough version of Mine Sweeper source code.

* 7/17/14
Updated MineSweeper to work with new Swift version.

iOS Simulator Screen Shot Jul 10, 2014, 9.56.08 AM

Swift and Sprite Kit version of Mine Sweeper source code