투케이2K

529. (ios/swift5) [유틸 파일] moveFile : 파일 이동 수행 본문

IOS

529. (ios/swift5) [유틸 파일] moveFile : 파일 이동 수행

투케이2K 2024. 6. 16. 12:34
반응형

[개발 환경 설정]

개발 툴 : XCODE

개발 언어 : SWIFT5

 

[소스 코드]

    // -----------------------------------------------------------------------------------------
    // MARK: - [파일 이동 수행]
    // -----------------------------------------------------------------------------------------
    func moveFile(movePath: String, childList:Array<String>, completion: @escaping (Bool, String)->()) {
        
        /*
        // -----------------------------------------
        [moveFile 메소드 설명]
        // -----------------------------------------
        1. 파일 이동 수행
        // -----------------------------------------
        2. 호출 방법 :
         
         let movePath = S_FinalData.HC_APP_LOG_FOLDER_NAME + "2"
         
         var childPath = Array<String>()
         childPath.append(S_FinalData.HC_APP_LOG_FOLDER_NAME + "/" + "twok.txt")
         
         C_App().moveFile(movePath:movePath, childList: childPath){(result, response) in
             
            S_Log._F_(description: "파일 이동 수행 결과 확인", data: ["\(result)", "\(response)"])
             
         }
         
        // -----------------------------------------
        */
        
        
        // [메인 큐에서 비동기 방식 실행 : UI 동작 실시]
        DispatchQueue.main.async {
            S_Log._F_(description: "파일 이동 수행 실시", data: nil)
            
            
            // [사전 인풋 데이터 널 체크 수행]
            if C_Util().stringNotNull(str: movePath) == true
                && C_Util().stringArrayNotNull(array_: childList) == true {
                
                let fileManager = FileManager.default // 파일 매니저 선언
                let documentsUrl =  fileManager.urls(for: .documentDirectory, in: .userDomainMask).first // 기본 경로 확인
                
                if C_Util().stringNotNull(str: documentsUrl?.description ?? "") == true {
                    
                    var childPaths = Array<String>()
                    
                    for i in stride(from: 0, through: childList.count-1, by: 1) { // [이동할 자식 파일이 있는지 확인]
                       
                        let item = String(describing: childList[i]) // forder/file
                        
                        let childFile = documentsUrl?.appendingPathComponent(item).path ?? ""
                        
                        if FileManager.default.fileExists(atPath: childFile) == true { // [저장 된 경로 있음]
                            childPaths.append(childFile) // [배열에 추가]
                        }
                        print("childFile :: \(childFile)")
                        
                    }
                    
                    
                    // [인풋 데이터와 파일 경로 검증 길이가 같은지 확인]
                    if childList.count == childPaths.count {
                        
                        // [이동 파일 경로 확인]
                        let moveFilePath = documentsUrl?.appendingPathComponent(movePath).path ?? ""
                        print("moveFilePath :: \(moveFilePath)")
                        
                        if FileManager.default.fileExists(atPath: moveFilePath) == false { // [저장 된 경로 없음 >> 폴더 생성 실시]
                            do {
                                
                                // [디렉토리 생성 실시]
                                try FileManager.default.createDirectory(atPath: moveFilePath, withIntermediateDirectories: true, attributes: nil)
                                
                            } catch {
                                completion(false, "[Exception] :: [1] :: \(error.localizedDescription)")
                                return
                            }
                        }
                        
                        
                        do {
                            
                            for i in stride(from: 0, through: childPaths.count-1, by: 1) {
                                
                                // [파일 명칭 파싱 수행]
                                let arrayFileName = childPaths[i].split(separator: "/")
                                
                                
                                try FileManager.default.moveItem(at: NSURL.fileURL(withPath: childPaths[i]), to: NSURL.fileURL(withPath: moveFilePath + "/move_" + arrayFileName[arrayFileName.count - 1]))
                                
                            }

                            completion(true, "[Success] :: file move success")
                            return
                            
                        } catch {
                            completion(false, "[Exception] :: [2] :: \(error.localizedDescription)")
                            return
                        }
                        
                    }
                    else {
                        completion(false, "[Error] :: child path length diff")
                        return
                    }
                    
                }
                else {
                    completion(false, "[Error] :: documentsUrl Is Null")
                    return
                }
            }
            else {
                completion(false, "[Error] :: Input Data Is Null")
                return
            }
            
        }
    }
 

[결과 출력]

 

 

반응형
Comments