투케이2K

551. (ios/swift5) [URLSession] FTP 접속 정보 사용해 FTP 서버 연결 가능 상태 확인 본문

IOS

551. (ios/swift5) [URLSession] FTP 접속 정보 사용해 FTP 서버 연결 가능 상태 확인

투케이2K 2024. 9. 13. 18:09
반응형

[개발 환경 설정]

개발 툴 : XCODE

개발 언어 : SWIFT5

 

[소스 코드]

    // -----------------------------------------------------------------------------------------
    // MARK: - [SEARCH FAST] : connectionFtpServer
    // -----------------------------------------------------------------------------------------
    func connectionFtpServer(tag: String, host: String, header: Dictionary<String, Any>?, userName: String, password: String, port: Int, completion: @escaping (Bool, String)->()) {
        
        /*
         // -----------------------------------------
         [connectionFtpServer 메소드 설명]
         // -----------------------------------------
         1. Get 방식 FTP 서버 연결 요청 메소드
         // -----------------------------------------
         2. 호출 방법 :
         
         let tag_ = "FTP 서버 연결 요청"
         let host_ = "test.com"
         let header_ : Dictionary<String, Any> = [:]
         let userName_ = "twok1234"
         let password_ = "admin"
         let port_ = 21
         
         
         C_FTP_Client_Module().connectionFtpServer(tag: tag_, host: host_, header: header_, userName: userName_, password: password_, port: port_){(result, response) in
             
             S_Log._F_(description: "FTP 연결 콜백 결과 확인", data: [response])
             
         }
         // -----------------------------------------
         3. 사전 설정 사항 :
         
         - 필요 info plist 설정
         [1] http 허용 : App Transport Security Settings >> Allow Arbitrary Loads >> YES
         // -----------------------------------------
         */
        
        
        // -----------------------------------------
        // [사전 방어 로직 체크]
        // -----------------------------------------
        if C_Util().stringNotNullMulti(data: [host, userName, password]) == false {
            
            // [콜백 반환]
            completion(false, "[ERROR] :: Input Connection Info Error")
            return
        }
        if host.startsWith(_string: "http") == true {
            
            // [콜백 반환]
            completion(false, "[ERROR] :: Host Start String Error")
            return
        }
        if port != 21 {
            
            // [콜백 반환]
            completion(false, "[ERROR] :: Connection Port Number Error")
            return
        }
        // -----------------------------------------
        
        
        
        // -----------------------------------------
        // [url 선언 실시] : ftp://username:password@ftp.example.com/path/to/file
        // -----------------------------------------
        let encodedUsername = userName.addingPercentEncoding(withAllowedCharacters: .urlUserAllowed) ?? ""
        let encodedPassword = password.addingPercentEncoding(withAllowedCharacters: .urlPasswordAllowed) ?? ""
        
        let urlData = "ftp://\(encodedUsername):\(encodedPassword)@\(host):\(port)"
        
        guard let ftpURL = URL(string: urlData)
        else {
            
            // [콜백 반환]
            completion(false, "[ERROR] :: Url Convert Error")
            return
        }
        // -----------------------------------------
        
        
        
        // -----------------------------------------
        // [URLRequest 생성 실시]
        // -----------------------------------------
        var requestURL = URLRequest(url: ftpURL)
        
        requestURL.httpMethod = "GET"
        
        requestURL.addValue("application/x-www-form-urlencoded; charset=utf-8;", forHTTPHeaderField: "Content-Type") // header settings
        requestURL.addValue("no-cache", forHTTPHeaderField: "Cache-Control") // header settings
        
        if C_Util().dicNotNull(dic_: header) == true {
            
            for key in header!.keys {
                
                requestURL.addValue("\(String(describing: header![key] ?? ""))", forHTTPHeaderField: "\(key)")
                
            }

        }
        
        
        S_Log._F_(description: C_FTP_Client_Module.ACTIVITY_NAME + " :: FTP 연결 [요청] 수행", data: [
            "TAG :: " + String(describing: tag),
            "TYPE :: GET >> REQUEST",
            "URL :: " + String(describing: urlData),
            "HEADER :: " + String(describing: header)
        ])
        
        
        // -----------------------------------------
        // [http 요쳥을 위한 URLSessionDataTask 생성]
        // -----------------------------------------
        let sessionConfig = URLSessionConfiguration.default
        sessionConfig.timeoutIntervalForRequest = C_FTP_Client_Module.TIME_OUT // [커넥션 타임 아웃 설정]
        sessionConfig.timeoutIntervalForResource = C_FTP_Client_Module.TIME_OUT // [리소스 읽기 , 쓰기]
        
        let session = URLSession(configuration: sessionConfig)
        
        let dataTask = session.dataTask(with: requestURL, completionHandler: { (data, response, error) in

            // ------------------------------------------------------
            // MARK: [error가 존재하면 종료]
            // ------------------------------------------------------
            // 사용자 정보 및 접속 비밀 번호 에러 : You do not have permission to access the requested resource.
            // ------------------------------------------------------
            // 서버 다운 및 도메인 정보가 올바르지 않은 상태 : The request timed out.
            // ------------------------------------------------------
            
            guard error == nil else {
                S_Log._F_(description: C_FTP_Client_Module.ACTIVITY_NAME + " :: FTP 연결 [결과] 실패", data: [
                    "TAG :: " + String(describing: tag),
                    "TYPE :: GET >> FAIL",
                    "URL :: " + String(describing: urlData),
                    "HEADER :: " + String(describing: header),
                    "ERROR :: \(error?.localizedDescription ?? "")"
                ])
                
                // [콜백 반환]
                completion(false, "[ERROR] :: \(error?.localizedDescription ?? "")")
                return
            }

            
            // [response 데이터 획득]
            let responseScript = response?.description ?? ""
            
            S_Log._F_(description: C_FTP_Client_Module.ACTIVITY_NAME + " :: FTP 연결 [결과] 확인", data: [
                "TAG :: " + String(describing: tag),
                "TYPE :: GET >> RESPONSE",
                "URL :: " + String(describing: urlData),
                "HEADER :: " + String(describing: header),
                "RESPONSE :: " + String(describing: responseScript)
            ])
            
            // [콜백 반환]
            completion(true, responseScript)
        })

        
        // [network 통신 실행]
        dataTask.resume()
    }
 

[결과 출력]

 

 

반응형
Comments