Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Slide DevCoach

Slide DevCoach

DevCoach 142 : iOS | Mengakses Data dari Server dalam Aplikasi iOS menggunakan URL Session

shabilla

April 08, 2024
Tweet

More Decks by shabilla

Other Decks in Programming

Transcript

  1. Position Akses Data dari Server dalam Aplikasi iOS dengan URLSession

    iOS Developer Gilang Ramadhan Curriculum Mobile Developer
  2. Developer Coaching #140 iOS Developer • Memahami cara kerja concurrency

    dan threading dalam Swift. • Memahami berbagai tipe dispatch dan threading untuk manajemen thread. • Memahami perbedaan antara serial dan concurrent, serta synchronous dan asynchronous. • Memahami cara terbaru untuk menangani proses dengan async/await.
  3. Learning Objectives • Pentingnya networking dalam pengembangan aplikasi iOS. •

    Fungsi URL Session sebagai tool networking. • Perbedaan setiap tipe dari URLSession • Cara mengubah data dengan format JSON iOS Developer
  4. iOS Developer Hampir 90% aplikasi yang tersedia di App Store

    memiliki fitur untuk mendapatkan data dari internet.
  5. API Contract An API contract is like a formal agreement

    or set of rules between the Android (front-end) and back-end development teams when creating software. Communication Consistency • Accelerating Integration Processes • Improved Development Efficiency • Maintaining Good Documentation iOS Developer Endpoint Name: Get All User Base URL: https://reqres.in URL Params: /api/users?page=1&per_page=10 Method: GET Response (JSON): { "page": Int, "per_page": Int, "total": Int, "total_pages": Int, "data": [ { "id": Int, "email": String, "first_name": String, "last_name": String, "avatar": String } ] }
  6. API Parameter For Example : https://reqres.in/api/users?page=1&per_page=10 • Path : “users”

    • Query 1 : “page” with value “1”. • Query 2 : “per_page” with value “10”. • Use “?” as separator before first parameter. • Use “&” as separator for the next parameter. • Use “=” to fill query with value. iOS Developer
  7. JSON Result iOS Developer id email first_name last_name avatar 1

    [email protected] George Bluth https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg 2 [email protected] Janet Weaver https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg
  8. URL Session URLSession adalah objek yang disediakan oleh Apple untuk

    melakukan koordinasi tugas transfer data antar jaringan. iOS Developer URLSession.shared.dataTask(with: url)
  9. Tipe dari URLSession • Default Session • Ephemeral Session •

    Background Session iOS Developer URLSession(configuration: .default) URLSession(configuration: .ephemeral) URLSession(configuration: .background(withIdentifier: "com.dicoding.background"))
  10. URL Session URLSessionTask memiliki beberapa jenis • Data Task •

    Download Task • Upload Task • WebSocket Task iOS Developer URLSessionTask URLSessionDownloadTask URLSessionDataTask URLSessionUploadTask
  11. Movie DB Kali ini, kita akan menggunakan Public API dari

    Movie DB. Baca selengkapnya di: https://www.dicoding.com/blog/registrasi -testing-themoviedb-api/ iOS Developer
  12. URL Component Sebuah struktur yang membaca alamat web (URL) menjadi

    bagian-bagian kecilnya dan juga membangun alamat web dari bagian-bagian tersebut. iOS Developer var components = URLComponents(string: "https://api.themoviedb.org/3/movie/popular")! components.queryItems = [ URLQueryItem(name: "api_key", value: apiKey), URLQueryItem(name: "language", value: language), URLQueryItem(name: "page", value: page) ] https://api.themoviedb.org/3/movie/popular?api_key=apiKey&language=language&page=page
  13. Method GET Gunakan Data Task untuk berkomunikasi dengan API melalui

    metode GET. DataTask terdiri dari 3 output. • data • response • error iOS Developer let request = URLRequest(url: components.url!) let task = URLSession.shared .dataTask(with: request) { data, response, error in guard let response = response as? HTTPURLResponse else { return } if let data = data { // MARK: Di sini digunakan untuk mengelola data API. } }
  14. Parsing JSON iOS Developer struct MovieResponse: Codable { let popularity:

    Double let posterPath: String let title: String let genres: [Int] let voteAverage: Double let overview: String let releaseDate: String enum CodingKeys: String, CodingKey { case popularity case posterPath = "poster_path" case title case genres = "genre_ids" case voteAverage = "vote_average" case overview case releaseDate = "release_date" } } struct MovieResponses: Codable { let page: Int let totalResults: Int let totalPages: Int let movies: [MovieResponse] enum CodingKeys: String, CodingKey { case page case totalResults = "total_results" case totalPages = "total_pages" case movies = "results" } }
  15. Parsing JSON iOS Developer let decoder = JSONDecoder() if let

    movies = try? Decoder .decode(MovieResponses.self, from: data) as MovieResponses { print("PAGE: \(movies.page)") print("TOTAL RESULTS: \(movies.totalResults)") print("TOTAL PAGES: \(movies.totalPages)") movies.movies.forEach { movie in print("TITLE: \(movie.title)") print("POSTER: \(movie.posterPath)") print("DATE: \(movie.releaseDate)") } } else { print("ERROR: Can't Decode JSON") }
  16. Custom Value iOS Developer struct MovieResponse: Codable { ... init(from

    decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) // MARK: Menentukan alamat gambar let path = try container.decode(String.self, forKey: .posterPath) posterPath = "https://image.tmdb.org/t/p/w300\(path)" // MARK: Mementukan tanggal rilis let dateString = try container.decode(String.self, forKey: .releaseDate) let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" releaseDate = dateFormatter.date(from: dateString)! // MARK: Untuk properti lainnya, cukup disesuaikan saja. popularity = try container.decode(Double.self, forKey: .popularity) ...
  17. Method Post iOS Developer var request = URLRequest(url: components.url!) request.httpMethod

    = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let jsonRequest = [ "value": 9.0 ] let jsonData = try! JSONSerialization.data(withJSONObject: jsonRequest, options: []) let task = URLSession.shared.uploadTask(with: request, from: jsonData) { data, response, error in guard let response = response as? HTTPURLResponse, let data = data else { return } if response.statusCode == 201 { print("DATA: \(data)") } } task.resume()
  18. iOS Developer Dalam merancang aplikasi, menguasai manajemen koneksi jaringan, URLSession

    untuk transfer data, dan kemampuan mengolah JSON adalah hal yang penting. Tidak hanya menghasilkan aplikasi yang responsif, tetapi juga memungkinkan pengalaman pengguna yang dinamis dan efisien dalam berinteraksi dengan web API.
  19. Feedback! Hadiah: • 1 Token Langganan Academy (30 Hari) *untuk

    pengisi feedback terpilih! dicoding.id/devcoachfeedback