다시 개발자

swiftui, macbook에 설치된 fastapi와 통신

까삼스 이삐 2023. 8. 16. 11:57
728x90
반응형

swiftui로 macbook에 설치된 fastapi server와 통신하는 방법입니다.

 

1. MacBook에 fastapi 설치

아래 글을 참조해 MacBook에 fastapi를 설치하고 샘플 코드를 구현해 서버를 구동합니다.

 

2022.12.06 - [다시 개발자] - fastapi 설치

 

fastapi 설치

fastapi 설치 및 샘플은 fastapi를 만든 Sebastián Ramírez가 직접 운영하는 사이트를 참조하면 됩니다. https://fastapi.tiangolo.com/ko/ FastAPI FastAPI FastAPI 프레임워크, 고성능, 간편한 학습, 빠른 코드 작성, 준

kka3seb.tistory.com

 

fastapi를 구동할 때 ip는 반드시 '0.0.0.0'로 해야 합니다.

uvicorn main:app --reload --host=0.0.0.0 --port=8000 

 

2. MacBook ip 확인

phone은 MacBook과 엄연히 다른 디바이스이기 때문에 macbook의 ip를 알아야 접근이 가능합니다.

터미널에서 $ ifconfig | grep inet을 입력, inet 옆에 있는 ip를 확인합니다.

$ ifconfig | grep inet

 

참고로, ifconfig로 나오는 ip는 내부 ip로 phone으로 접근하기 위해서는 macbook과 phone이 같은 네트워크 환경에 있어야 합니다.

좀 더 쉽게 말해, macbook과 phone 모두 동일한 wifi로 네트워크 설정이 되어야 합니다.

 

728x90

3. swiftui로 구현

ContentView를 다음과 같이 구현합니다.

import SwiftUI


struct ContentView: View {
    
    @State var textVal:String = "Hello, world!"
    
    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text(textVal)
            Button("FastAPI 연동") {
                Task {
                    do {
                        let myS = try await testCallFastAPI()
                        textVal = myS.q
                    } catch let error as myError {
                        print(error)
                    }
                }
            }
        }
        .padding()
    }
    
    func testCallFastAPI() async throws -> myStruct {
        
        let baseUrl ="http://172.30.1.66:8000/"        // macbook ip, fastapi port
        let url = URL(string: baseUrl+"items/5?q=somequery")!
        var request = URLRequest(url: url)
        
        request.httpMethod = "GET"


        request.addValue("application/json", forHTTPHeaderField: "Accept")
        let (data, response) = try await URLSession.shared.data(for: request)
        
        if let response = (response as? HTTPURLResponse)  {
            if response.statusCode == 401{
                throw myError.msg(desc: "No matched User")
            }
            if response.statusCode != 200{
                throw myError.msg(desc:"other Error")
            }
            
        }else{
            throw myError.msg(desc:"Error while fetching data")
        }
        
        let decodedData = try JSONDecoder().decode(myStruct.self, from: data)
        print("test data: ", decodedData)
        return decodedData
    }
}


struct myStruct : Codable {
    let item_id: Int
    let q: String
}


enum myError:Error {
    case msg(desc:String)
}

 

실행 화면입니다.

 

728x90
반응형