iOS_Intermediate
iOS_Intermediate
func fetchPosts() {
let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else { return }
do {
let posts = try JSONDecoder().decode([Post].self, from: data)
print(posts)
} catch {
print("Failed to decode JSON: \(error.localizedDescription)")
}
}
task.resume()
}
func fetchUsers() {
let url = URL(string: "https://jsonplaceholder.typicode.com/users")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else { return }
do {
let users = try JSONDecoder().decode([User].self, from: data)
for user in users {
print("User: \(user.name), Email: \(user.email)")
}
} catch {
print("Error parsing JSON: \(error)")
}
}
task.resume()
}
func saveContext() {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
do {
try context.save()
} catch {
print("Failed to save the item: \(error)")
}
Fetching Data
// Fetching data from Core Data
let fetchRequest = NSFetchRequest<Item>(entityName: "Item")
do {
let items = try context.fetch(fetchRequest)
for item in items {
print("Item: \(item.name ?? "No Name")")
}
} catch {
print("Failed to fetch items: \(error)")
}
func scheduleBackgroundTask() {
let taskRequest = BGAppRefreshTaskRequest(identifier: "com.example.app.refresh")
taskRequest.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60) // 15 minutes from
now
do {
try BGTaskScheduler.shared.submit(taskRequest)
} catch {
print("Could not schedule app refresh: \(error)")
}
}
func scheduleLocalNotification() {
let content = UNMutableNotificationContent()
content.title = "Hello!"
content.body = "This is a local notification."
content.sound = UNNotificationSound.default
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print("Error scheduling notification: \(error)")
}
}
}
Handling Notifications
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
return true
}
}
advertisement
Unit Testing in Xcode Tutorial
Unit testing in Xcode is a crucial practice that allows developers to validate the functionality of
individual components of their iOS applications. By writing tests for individual functions or methods,
developers can ensure that the code behaves as expected and can quickly identify when changes
introduce bugs. XCTest is the framework provided by Apple for writing unit tests in Xcode, supporting
assertions to verify results and offering a way to automate testing processes.
Copy
Testing a Simple Function
import XCTest
func testFetchingData() {
let expectation = self.expectation(description: "Data fetched")
fetchData { result in
self.data = result
expectation.fulfill()
}
waitForExpectations(timeout: 5) { error in
XCTAssertNil(error, "Expectation timed out")
XCTAssertEqual(self.data, "Expected Data")
}
}
Testing Performance
import XCTest
Using UISlider
import UIKit