본문 바로가기

Swift

iCloud로 파일 관리 - setUbiquitous

클라우드에 파일을 저장하려고 여기저기 다 뒤지고 다녔는데, 그 중 ubiquity 애들을 이용하는 것이 가장 간단해보였다. 이 애들은 Cloudkit을 import하지 않고서도 사용이 가능하다.


특히 setUbiquitous()를 이용하여 로컬 파일을 클라우드로 보내고 클라우드 파일을 로컬로 다운로드가 가능하다고 하여 이 메소드를 사용해보았다.


허나 문제점이 발생.. 일단 로컬 파일을 클라우드로 저장하는 소스를 보자.

아래 소스의 앞 부분에

let containerURL = fileManager.URLForUbiquityContainerIdentifier(nil)

를 선언하여 클라우드의 기본 디렉토리 정보를 가져오도록 한다.


if let directory = cloudDocumentsDirectory{

    let destinationUrl = directory.URLByAppendingPathComponent(fileName)

    let dirPath = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first
    if let path = dirPath {
        let localURL = path.URLByAppendingPathComponent(fileName)
        debugPrint("Now moving this file into the cloud...")

        // local file을 클라우드에 저장
        if !doesDocumentsDirectoryExist(directory) {
            // 클라우드에 document폴더가 없으면 폴더를 만들어야지
            // fileManager.createDirectoryAtPath를 이용
        }

        var savingError: NSError?
        do {
            // 같은 파일이 있는지 확인
            if fileManager.fileExistsAtPath(destinationUrl.path!) {
                // 있으면 파일 제거
                debugPrint("remove target file in the cloud...")
                try fileManager.removeItemAtURL(destinationUrl)

            }

            // 첫 번째 인자가 true면 로컬 파일을 클라우드로 move (copy가 아니다!)
            try fileManager.setUbiquitous(true,
                                          itemAtURL: localURL,
                                          destinationURL: destinationUrl)
            debugPrint("Successfully moved the file to the cloud...")
        } catch let error1 as NSError {
            savingError = error1
            if let error = savingError {
                debugPrint("Failed to move the file to the cloud = \(error)")
            }
        }
    }
}



별 이상이 없어 보이는 소스이나 실행시키고 나니 뭔가 이상한 점이 발견되었다. 그것은 로컬 파일을 클라우드로 저장한 후 로컬 파일이 없어지는 현상이었다.

실제로 좀 검색해보았더니 이 메소드는 파일 copy가 아니고 move라고 한다. 헐~ 이런 병맛같은 경우가..


이 메소드에 대해 조금 더 알아보면.. 첫 번째 인자로 bool 값을 받는데,

try fileManager.setUbiquitous(true,
                              itemAtURL: localURL,
                              destinationURL: destinationUrl)

이 인자가 true이면 로컬 파일을 클라우드로 move이며 false인 경우에는 그 반대이다.

물론 주의점은 copy가 아닌 move라는 점..