Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
629 changes: 629 additions & 0 deletions PokemonPhoneBook.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>SchemeUserState</key>
<dict>
<key>PokemonPhoneBook.xcscheme_^#shared#^_</key>
<dict>
<key>orderHint</key>
<integer>0</integer>
</dict>
</dict>
</dict>
</plist>
79 changes: 79 additions & 0 deletions PokemonPhoneBook/AppDelegate.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
//
// AppDelegate.swift
// PokemonPhoneBook
//
// Created by 내일배움캠프 on 12/6/24.
//

import UIKit
import CoreData

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}

// MARK: UISceneSession Lifecycle

func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
// Called when a new scene session is being created.
// Use this method to select a configuration to create the new scene with.
return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}

func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
// Called when the user discards a scene session.
// If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
// Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}

// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "PokemonPhoneBook")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()

// MARK: - Core Data Saving support

func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}

}

Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"colors" : [
{
"idiom" : "universal"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
35 changes: 35 additions & 0 deletions PokemonPhoneBook/Assets.xcassets/AppIcon.appiconset/Contents.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"images" : [
{
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "dark"
}
],
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
},
{
"appearances" : [
{
"appearance" : "luminosity",
"value" : "tinted"
}
],
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
6 changes: 6 additions & 0 deletions PokemonPhoneBook/Assets.xcassets/Contents.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"info" : {
"author" : "xcode",
"version" : 1
}
}
25 changes: 25 additions & 0 deletions PokemonPhoneBook/Base.lproj/LaunchScreen.storyboard
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="13122.16" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="13104.12"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" xcode11CocoaTouchSystemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<viewLayoutGuide key="safeArea" id="6Tk-OE-BBY"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>
109 changes: 109 additions & 0 deletions PokemonPhoneBook/Controllers/AddPhoneBookViewController.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import UIKit
import CoreData
import Alamofire

class AddPhoneBookViewController: UIViewController {

private let addPhoneBookView = AddPhoneBookView()

var phoneBook: NSManagedObject?
var isEditingMode: Bool = false

override func loadView() {
view = addPhoneBookView
}

override func viewDidLoad() {
super.viewDidLoad()
setupNavigationBar()
configureEditingMode()
addActions()
}

private func setupNavigationBar() {
let addButton = UIBarButtonItem(
title: "적용",
style: .plain,
target: self,
action: #selector(addButtonTapped)
)

navigationItem.title = "연락처 추가"
navigationItem.rightBarButtonItem = addButton
}

private func addActions() {
addPhoneBookView.createButton.addTarget(self, action: #selector(createButtonTapped), for: .touchUpInside)
}

@objc private func createButtonTapped() {
let randomNumber = Int.random(in: 0...1000)
guard let url = URL(string: "https://pokeapi.co/api/v2/pokemon/\(randomNumber)") else { return }

PokeAPIManager.shared.fetchPokemonData(url: url) { [weak self] (result: Result<PokeMon, AFError>) in
guard let self = self else { return }
switch result {
case .success(let pokemon):
guard let imageUrl = URL(string: pokemon.sprites.frontDefault) else { return }
PokeAPIManager.shared.fetchImage(url: imageUrl) { imageResult in
switch imageResult {
case .success(let image):
DispatchQueue.main.async {
self.addPhoneBookView.updateImage(image)
}
case .failure(let error):
print("이미지 로드 실패: \(error.localizedDescription)")
}
}
case .failure(let error):
print("데이터 로드 실패: \(error)")
}
}
}

@objc private func addButtonTapped() {
guard let formData = addPhoneBookView.getFormData() else {
showAlert(message: "이미지 생성과 이름, 전화번호를 모두 입력하세요.")
return
}
if isEditingMode {
updateData(name: formData.name, phoneNumber: formData.phoneNumber, image: formData.image!)
} else {
createData(name: formData.name, phoneNumber: formData.phoneNumber, image: formData.image!)
}
navigationController?.popViewController(animated: true)
}

private func showAlert(message: String) {
let alert = UIAlertController(title: "알림", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "확인", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}

private func createData(name: String, phoneNumber: String, image: UIImage) {
if CoreDataManager.shared.createPhoneBook(name: name, phoneNumber: phoneNumber, image: image) {
print("연락처 저장 성공")
} else {
print("연락처 저장 실패")
}
}

private func updateData(name: String, phoneNumber: String, image: UIImage) {
guard let phoneBook = phoneBook else { return }
if CoreDataManager.shared.updatePhoneBook(phoneBook: phoneBook, name: name, phoneNumber: phoneNumber, image: image) {
print("연락처 업데이트 성공")
} else {
print("연락처 업데이트 실패")
}
}

private func configureEditingMode() {
guard isEditingMode, let phoneBook = phoneBook else { return }
let phoneBook1 = PhoneBook(
name: phoneBook.value(forKey: PokemonPhoneBook.Key.name) as? String ?? "",
phoneNumber: phoneBook.value(forKey: PokemonPhoneBook.Key.phoneNumber) as? String ?? "",
image: (phoneBook.value(forKey: PokemonPhoneBook.Key.image) as? Data).flatMap { UIImage(data: $0) }
)
addPhoneBookView.updateView(with: phoneBook1)
}
}
Loading