투케이2K

184. (swift5/xcode) [유틸 파일] set_File_Text_Append : 앱 파일 저장소에 특정 텍스트 파일 내용 Append 추가 본문

Swift

184. (swift5/xcode) [유틸 파일] set_File_Text_Append : 앱 파일 저장소에 특정 텍스트 파일 내용 Append 추가

투케이2K 2023. 12. 9. 16:33
반응형

[개발 환경 설정]

개발 툴 : XCODE

개발 언어 : SWIFT5

 

[소스 코드]

    // -----------------------------------------------------------------------------------------
    // MARK: - [앱 파일 저장소 텍스트 파일 쓰기 수행]
    // -----------------------------------------------------------------------------------------
    func set_File_Text_Append(folderName: String, fileName: String, text: String) {
        
        /*
        // -----------------------------------------
        [set_File_Text_Append 메소드 설명]
        // -----------------------------------------
        1. 앱 파일 저장소 텍스트 파일 쓰기 수행
        // -----------------------------------------
        2. 호출 방법 :
         
         C_App().set_File_Text_Append(folderName: "TEST_FOLDER", fileName: "TWOK.txt", text: "hello")
         C_App().set_File_Text_Append(folderName: S_FinalData.HC_APP_LOG_FOLDER_NAME, fileName: S_FinalData.HC_APP_USE_FILE_NAME, text: "hello")
        // -----------------------------------------
        4. 참고 info plist 설정 :
         
         아이폰 파일 접근 설정 : Supports opening documents in place : YES
         아이튠즈 공유 설정 : Application supports iTunes file sharing : YES
        // -----------------------------------------
        */

        
        // [변수 선언]
        var M_LOG = ""
        var fileWritePath = ""


        // [로직 처리 실시]
        let fileManager = FileManager.default // 파일 매니저 선언
        let documentsUrl =  fileManager.urls(for: .documentDirectory, in: .userDomainMask).first // 기본 경로 확인
        
        if documentsUrl != nil && C_Util().stringNotNull(str: fileName) == true {
            
            if C_Util().stringNotNull(str: documentsUrl?.description ?? "") == true {
                
                if C_Util().stringNotNull(str: folderName) == true { // [폴더 명칭이 널이 아닌 경우]
                    
                    fileWritePath = documentsUrl?.appendingPathComponent(folderName).path ?? ""
                    
                    if FileManager.default.fileExists(atPath: fileWritePath) == false { // [저장 된 경로 없음 >> 폴더 생성 실시]
                        do {
                            
                            // [디렉토리 생성 유무 확인]
                            try FileManager.default.createDirectory(atPath: fileWritePath, withIntermediateDirectories: true, attributes: nil)
                            
                            if (fileWritePath.hasSuffix("/") == true){
                                fileWritePath = fileWritePath + fileName
                            }
                            else {
                                fileWritePath = fileWritePath + "/" + fileName
                            }
                            
                            M_LOG = "[Folder Create] :: "
                            
                            let contentData = "".data(using: .utf8)
                            
                            do {
                                try contentData?.write(to: NSURL.fileURL(withPath: fileWritePath), options: Data.WritingOptions.atomic)
                                
                                M_LOG = M_LOG + "[Success] :: [Write] :: File"
                                        
                            } catch {
                                M_LOG = "[Exception] :: [Write] :: \(error.localizedDescription)"
                            }
                            
                        } catch {
                            M_LOG = "[Exception] :: \(error.localizedDescription)"
                        }
                    }
                    else { // [폴더 >> 있음]
                        M_LOG = "[Folder Exists] :: "
                        
                        if (fileWritePath.hasSuffix("/") == true){
                            fileWritePath = fileWritePath + fileName
                        }
                        else {
                            fileWritePath = fileWritePath + "/" + fileName
                        }
                        
                        if FileManager.default.fileExists(atPath: fileWritePath) == true { // [파일 존재]
                            
                            let contentData = text.data(using: .utf8)
                            
                            if let handle = try? FileHandle(forWritingTo: NSURL.fileURL(withPath: fileWritePath)) {
                                handle.seekToEndOfFile() // moving pointer to the end
                                handle.write(contentData!) // adding content
                                handle.closeFile() // closing the file
                                
                                M_LOG = M_LOG + "[Success] :: [Append] :: File"
                            }
                            else {
                                M_LOG = M_LOG + "[Fail] :: [Append] :: File"
                            }
                            
                        }
                        else { // [파일 없음]
                            do {
                                let contentData = text.data(using: .utf8)
                                
                                try contentData?.write(to: NSURL.fileURL(withPath: fileWritePath), options: Data.WritingOptions.atomic)
                                
                                M_LOG = M_LOG + "[Success] :: [Write] :: File"
                                        
                            } catch {
                                M_LOG = "[Exception] :: [Write] :: \(error.localizedDescription)"
                            }
                        }
                        
                    }
                    
                }
                else { // [폴더 명칭 없음 >> document 에 저장]
                    M_LOG = "[Folder Default] :: "
                    
                    fileWritePath = documentsUrl?.path ?? ""
                    
                    if (fileWritePath.hasSuffix("/") == true){
                        fileWritePath = fileWritePath + fileName
                    }
                    else {
                        fileWritePath = fileWritePath + "/" + fileName
                    }
                    
                    
                    if FileManager.default.fileExists(atPath: fileWritePath) == true { // [파일 존재]
                        
                        let contentData = text.data(using: .utf8)
                        
                        if let handle = try? FileHandle(forWritingTo: NSURL.fileURL(withPath: fileWritePath)) {
                            handle.seekToEndOfFile() // moving pointer to the end
                            handle.write(contentData!) // adding content
                            handle.closeFile() // closing the file
                            
                            M_LOG = M_LOG + "[Success] :: [Append] :: File"
                        }
                        else {
                            M_LOG = M_LOG + "[Fail] :: [Append] :: File"
                        }
                        
                    }
                    else { // [파일 없음]
                        do {
                            let contentData = text.data(using: .utf8)
                            
                            try contentData?.write(to: NSURL.fileURL(withPath: fileWritePath), options: Data.WritingOptions.atomic)
                            
                            M_LOG = M_LOG + "[Success] :: [Write] :: File"
                                    
                        } catch {
                            M_LOG = "[Exception] :: [Write] :: \(error.localizedDescription)"
                        }
                    }
                }
                
            }
            else {
                M_LOG = "[ERROR] :: documentsUrl Is Null"
            }
            
        }
        else {
            M_LOG = "[ERROR] :: documentDirectory And File Name Is Null"
        }

        
        // [로그 출력 실시]
        S_Log._D_(description: "앱 파일 저장소 텍스트 파일 쓰기 수행", data: [
            "INPUT [folderName] :: \(folderName)",
            "INPUT [fileName] :: \(fileName)",
            "M_LOG :: \(M_LOG)",
            "SAVE_PATH :: \(fileWritePath)"
        ])
        
    }
 

[결과 출력]


 
반응형
Comments