[Project] 연락처 앱 만들기 ②

JJOOEE__·2024년 7월 18일
0

Today I Learned....

목록 보기
17/19
post-thumbnail

🧑🏻‍💻 Level 4 - API 연결
  • 랜덤 이미지 생성 버튼을 구현합니다.

  • 버튼을 클릭할때마다 랜덤한 포켓몬 이미지를 불러옵니다.

  • 포켓몬 API 를 생성해서 랜덤 포켓몬 이미지를 프로필로 지정해봅시다.

  • https://pokeapi.co/

  • API 명세

    • GET 메서드 사용
    • URL: https://pokeapi.co/api/v2/pokemon/{1~1000사이의랜덤숫자입력}

Json Response 형태 (더 많은 정보를 받을 수 있지만 이 정도만 받아봅시다.)

여기서 front_default 가 포켓몬의 정면 이미지 url 입니다.


//
//  PokemonIMage.swift

import Foundation
import UIKit

func ramdomPokemonImage(completion: @escaping (UIImage?) -> Void) {
    let randomID = Int.random(in: 1...1000)
    let urlString = "https://pokeapi.co/api/v2/pokemon/\(randomID)"
    guard let url = URL(string:  urlString) else {
        completion(nil)
        return
    }

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        DispatchQueue.global().async {
            if let error = error {
                print("Error feching Pokemon data: \(error)")
                completion(nil)
            }
            return
        }
        guard let data = data,
              let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
              let sprites = json["sprites"] as? [String: Any],
              let imageUrlString = sprites["front_default"] as? String,
              let imageUrl = URL(string: imageUrlString),
              let imageData = try? Data(contentsOf: imageUrl),
              let image = UIImage(data: imageData) else {
            DispatchQueue.main.async {
                completion(nil)
            }
            return
        }

        DispatchQueue.main.async {
            completion(image)
        }
    }

task.resume()
}
//
//  UserEditVC.swift
//  Created by Lee-Juhee on 7/16/24.

import UIKit
import SnapKit

class UserEditVC: UIViewController {


    let userProfileImage: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit
        imageView.layer.borderWidth = 1
        imageView.layer.cornerRadius = 80
        imageView.clipsToBounds = true
        return imageView
    }()

    lazy var randomImageBtn: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("랜덤 이미지 생성", for: .normal)
        button.addTarget(self, action: #selector(randomImageBtntapped), for: .touchUpInside)
        return button
    }()

    let nameTextView: UITextView = {
        let textView = UITextView()
        textView.layer.borderWidth = 1
        textView.layer.borderColor = UIColor.gray.cgColor
        return textView
    }()

    let numTextView: UITextView = {
        let textView = UITextView()
        textView.layer.borderWidth = 1
        textView.layer.borderColor = UIColor.gray.cgColor
        return textView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
        
        view.addSubview(userProfileImage)
        view.addSubview(randomImageBtn)
        view.addSubview(nameTextView)
        view.addSubview(numTextView)


        UserNaviBarSetup()
        UserSetupConstraints()
    }

    //navigationBarSetup 설정
    private func UserNaviBarSetup() {
//        let navigationItem = UINavigationItem(title: "친구 목록")
        let okBtn = UIBarButtonItem(title: "적용", style: .plain, target: self, action: #selector(btnTapped))
        self.navigationItem.rightBarButtonItem = okBtn
        self.title = "연락처 추가"
    }
    func UserSetupConstraints() {
        //userProfileImage 제약조건
        userProfileImage.snp.makeConstraints {
            $0.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(40)
            $0.centerX.equalToSuperview()
            $0.width.height.equalTo(160)
        }
        //randomImageBtn 제약조건
        randomImageBtn.snp.makeConstraints {
            $0.top.equalTo(userProfileImage.snp.bottom).offset(20)
            $0.centerX.equalToSuperview()
        }
        //nameTextView 제약조건
        nameTextView.snp.makeConstraints {
            $0.top.equalTo(randomImageBtn.snp.bottom).offset(30)
            $0.leading.equalToSuperview().offset(20)
            $0.trailing.equalToSuperview().offset(-20)
            $0.height.equalTo(40)
        }
        //numTextView 제약조건
        numTextView.snp.makeConstraints {
            $0.top.equalTo(nameTextView.snp.bottom).offset(30)
            $0.leading.equalToSuperview().offset(20)
            $0.trailing.equalToSuperview().offset(-20)
            $0.height.equalTo(40)
        }
    }

    // addBtnTapped 메서드 생성
    @objc func btnTapped() {

    }

    @objc func randomImageBtntapped(){
        ramdomPokemonImage { [weak self] image in
            DispatchQueue.main.async {
                self?.userProfileImage.image = image
            }
        }
    }
}

💡 공부한 내용 : API, UrlSession

🍀🍏🍎 ◻️💡👆 🌈 ①②③④⑤⑥⑦⑧⑨

profile
개발이 어려운 나를 위한... 개발노트

0개의 댓글