Alex Huang
May 17
Estimated reading time: 8 minute(s)
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello, World!")
}
}
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = UIButton(type: .system)
button.setTitle("Tap me!", for: .normal)
button.frame = CGRect(x: 100, y: 100, width: 100, height: 50)
view.addSubview(button)
}
}
import CoreData
// Define a new entity and save it
let entity = NSEntityDescription.entity(forEntityName: "Person", in: context)
let newPerson = NSManagedObject(entity: entity!, insertInto: context)
newPerson.setValue("John", forKey: "name")
do {
try context.save()
} catch {
print("Failed saving")
}
// Fetch the saved data
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
print(data.value(forKey: "name") as! String)
}
} catch {
print("Failed fetching")
}
import Combine
let publisher = Just("Hello, Combine!")
let subscriber = Subscribers.Sink<String, Never>(
receiveCompletion: { completion in
print("Received completion: \(completion)")
},
receiveValue: { value in
print("Received value: \(value)")
}
)
publisher.subscribe(subscriber)
import ARKit
import SceneKit
import UIKit
class ViewController: UIViewController, ARSCNViewDelegate {
var sceneView: ARSCNView!
override func viewDidLoad() {
super.viewDidLoad()
sceneView = ARSCNView(frame: self.view.frame)
self.view.addSubview(sceneView)
sceneView.delegate = self
let scene = SCNScene()
sceneView.scene = scene
let box = SCNBox(width: 0.1, height: 0.1, length: 0.1, chamferRadius: 0.01)
let boxNode = SCNNode(geometry: box)
boxNode.position = SCNVector3(0, 0, -0.5)
scene.rootNode.addChildNode(boxNode)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let configuration = ARWorldTrackingConfiguration()
sceneView.session.run(configuration)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
sceneView.session.pause()
}
}
import HealthKit
let healthStore = HKHealthStore()
if HKHealthStore.isHealthDataAvailable() {
let stepCountType = HKQuantityType.quantityType(forIdentifier: .stepCount)!
let readDataTypes = Set([stepCountType])
healthStore.requestAuthorization(toShare: nil, read: readDataTypes) { success, error in
if success {
let query = HKSampleQuery(sampleType: stepCountType, predicate: nil, limit: 0, sortDescriptors: nil) { query, results, error in
guard let results = results as? [HKQuantitySample] else {
return
}
for result in results {
print("Steps: \(result.quantity)")
}
}
healthStore.execute(query)
}
}
}
import CloudKit
let container = CKContainer.default()
let publicDatabase = container.publicCloudDatabase
// Save a record
let record = CKRecord(recordType: "Note")
record["content"] = "Hello, CloudKit!"
publicDatabase.save(record) { record, error in
if let error = error {
print("Error saving record: \(error)")
} else {
print("Record saved successfully")
}
}
// Fetch records
let query = CKQuery(recordType: "Note", predicate: NSPredicate(value: true))
publicDatabase.perform(query, inZoneWith: nil) { records, error in
if let error = error {
print("Error fetching records: \(error)")
} else {
if let records = records {
for record in records {
print("Fetched record: \(record["content"])")
}
}
}
}
import WidgetKit
import SwiftUI
struct SimpleEntry: TimelineEntry {
let date: Date
}
struct SimpleWidgetEntryView: View {
var entry: SimpleEntry
var body: some View {
Text(entry.date, style: .time)
}
}
@main
struct SimpleWidget: Widget {
let kind: String = "SimpleWidget"
var body: some WidgetConfiguration {
StaticConfiguration(kind: kind, provider: SimpleProvider()) { entry in
SimpleWidgetEntryView(entry: entry)
}
.configurationDisplayName("Simple Widget")
.description("This is an example widget.")
}
}
struct SimpleProvider: TimelineProvider {
func placeholder(in context: Context) -> SimpleEntry {
SimpleEntry(date: Date())
}
func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
let entry = SimpleEntry(date: Date())
completion(entry)
}
func getTimeline(in context: Context, completion: @escaping (Timeline<SimpleEntry>) -> ()) {
var entries: [SimpleEntry] = []
let currentDate = Date()
for hourOffset in 0 ..< 5 {
let entryDate = Calendar.current.date(byAdding: .hour, value: hourOffset, to: currentDate)!
let entry = SimpleEntry(date: entryDate)
entries.append(entry)
}
let timeline = Timeline(entries: entries, policy: .atEnd)
completion(timeline)
}
}