How to WebDAV on macOS

Home 📂 Blog Posts

Published at: 2018-09-11 23:28:03 +0000


WebDAV was really the "web" we were promised that we never really got.


It is a quick and easy way to have a standard API for a directory of files. It is built into Apache, just enable the web_dav and web_dav_fs modules and enable the "Dav" directive in a directory. You will probably limit the verbs to the read only ones (GET, HEAD, OPTIONS, PROPFIND).


To list the contents of a directory on macOS you can use the PROPFIND HTTP verb.


  NSURL *webURL = [NSURL URLWithString:@"https://webdav/URL"];

  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:webURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];

  [request setHTTPMethod:@"PROPFIND"];

  [request setValue:@"1" forHTTPHeaderField:@"Depth"];

  NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

  

    NSXMLDocument *doc = [[NSXMLDocument alloc] initWithData:data options:NSXMLNodeOptionsNone error:nil];


The file system directly maps onto an XML document. That NSURLSession request above gives you this XML:


<?xml version="1.0" encoding="utf-8"?>

<D:multistatus xmlns:D="DAV:" xmlns:ns0="DAV:">

  <D:response xmlns:lp1="DAV:">

    <D:href>/webdav/</D:href>

    <D:propstat>

      <D:prop>

        <lp1:resourcetype>

          <D:collection/>

        </lp1:resourcetype>

      </D:prop>

      <D:status>HTTP/1.1 200 OK</D:status>

    </D:propstat>

  </D:response>

  <D:response xmlns:lp1="DAV:">

    <D:href>/webdav/testpost%20two.rtf</D:href>

    <D:propstat>

      <D:prop>

        <lp1:resourcetype/>

      </D:prop>

      <D:status>HTTP/1.1 200 OK</D:status>

    </D:propstat>

  </D:response>

</D:multistatus>


So walking each post in the directory is a simple case of:


  NSArray *elements = [[doc rootElement] elementsForName:@"D:response"];

  [elements enumerateObjectsUsingBlock:^(NSXMLElement *obj, NSUInteger idx, BOOL * _Nonnull stop) {

    NSString *filename = [[[obj elementsForName:@"D:href"] firstObject] stringValue];


Too bad this never really caught on. I will enjoy it while I can. And so can you!




Generated by Max Space

VKHWu1N+ZijnViN/pggbh7
kNuNqbpytYEWnQYyBJjNM=