Search code examples
swiftfilegrand-central-dispatch

How to get the file descriptor for DispatchIO using Swift?


I am trying to convert the below Objective-C code to Swift.

-(void)openChannelWithURL:(NSURL*)anURL {
   NSString* filePath = [anURL path];
   self.channel = dispatch_io_create_with_path(DISPATCH_IO_RANDOM,
                      [filePath UTF8String],   // Convert to C-string
                      O_RDONLY,                // Open for reading
                      0,                       // No extra flags
                      dispatch_get_main_queue(),
                      ^(int error){
                         // Cleanup code for normal channel operation.
                         // Assumes that dispatch_io_close was called elsewhere.
                         if (error == 0) {
                            dispatch_release(self.channel);
                            self.channel = NULL;
                         }
                      });
}

Using DispatchIO, the init requires a file descriptor. How to get a file descriptor?

public mutating func openChannelWithURL(anURL: URL) {
    let filePath: String = anURL.path
    DispatchIO.init(type: .stream, fileDescriptor: ?, queue: DispatchQueue.global()) { code in
        print("code: \(code)")
    }
}

I am trying to open a file in write only mode which will append data to the file asynchronously.


Solution

  • You don’t have a file descriptor. You have a file path. You’re calling the wrong initializer. You want this one:

    https://developer.apple.com/documentation/dispatch/dispatchio/2892309-init