Detect if video is still being written to

So, I'm trying to write a function to detect if a video file is currently being recorded to. The purpose is if it is, than you can't delete the file or rename it. Here's what I have:


public func fileSizeDetection(url: URL) -> Int{
    
    let tempFile = URL(string:(try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).absoluteString) + "tempFile")
    
    let keys : Set<URLResourceKey> = [URLResourceKey.fileSizeKey]
    
    
    do{
        try FileManager.default.copyItem(at: url, to: tempFile!)
        usleep(5000)
    }
    catch{
        print (error.localizedDescription)
    }
    
    let tempValues = try! tempFile!.resourceValues(forKeys: keys)
    let tempSize = tempValues.fileSize!
    let permValues = try! url.resourceValues(forKeys: keys)
    let permSize = permValues.fileSize!
    let difference = permSize - tempSize
    
    do{
        try FileManager.default.removeItem(at: tempFile!)
    }
    catch{
        print (error.localizedDescription)
    }
    
    return difference
}


So, I it starts by passing the URL to test. Than it creates a temporary copy of the file which is supposed to be a snapshot of it. Than it sleeps for a second, and compares the current file size to the copied file size. If there's no difference than it's not a recording in progress. Finally it deletes the temp copy.


The issue I'm having, is that tempFile and the original URL are the same size! I tried to increase usleep, but it still doesn't work. Can anyone please tell me what I'm doing wrong!

NSFileCoordinator
does block the main thread.

Cool. If that works then you should be able to do the work async using

-coordinateAccessWithIntents:queue:byAccessor:
(or one of the higher-level wrappers around that, like
-coordinateReadingItemAtURL:options:error:byAccessor:
).

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"
Accepted Answer

It ended up being very simple. I looked at all of the options you guys showed me, but in the end my original function just needed to be modified a little.


func detectIfRecording(url: URL) -> Int {
        
        let keys: Set<URLResourceKey> = [URLResourceKey.fileSizeKey]
        let values1 = try! url.resourceValues(forKeys: keys)
        let bytes1 = Int64.init((values1.fileSize!))
        usleep(250000)
        let values2 = try! URL(fileURLWithPath: url.path).resourceValues(forKeys: keys)
        let bytes2 = Int64.init((values2.fileSize!))
        if bytes2 > bytes1{            
            return 1
        }else{
            return 0
        }
}



I only need to check the newest video, not every single one.

Detect if video is still being written to
 
 
Q