Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List files in iTunes shared folder using Swift

I would like to list all files in my iTunes shared folder in a 'Table View' using Swift.
I check on Google and nobody talk about it, it look like it's a uncommon need, so if anyone can help it would be really helpful.

EDIT: I found three links talking about it but in Objective-C, I have no experience in this language. If someone understand this, here are the links.

http://www.exampledb.com/objective-c-get-itunes-file-sharing-folder-files-with-full-path.htm
http://www.infragistics.com/community/blogs/stevez/archive/2013/10/14/ios-objective-c-working-with-files.aspx
http://www.raywenderlich.com/1948/itunes-tutorial-for-ios-how-to-integrate-itunes-file-sharing-with-your-ios-app

like image 260
VivienG Avatar asked Oct 06 '14 19:10

VivienG


1 Answers

Based on this objective-C tutorial http://mobiforge.com/design-development/importing-exporting-documents-ios, I created three methods: listFilesFromDocumentsFolder which returns a list of the names of all documents I have in the apps iTunes shared folder and loadFileFromDocumentsFolder which loads the url for a given filename and passes the url to handleDocumentOpenUrl to load the file on a UIWebView. Find below the three methods. You can also download the project from github: https://github.com/Euniceadu/Load-Shared-Documents

listFilesFromDocumentsFolder

func listFilesFromDocumentsFolder() {
    var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    var documentsDirectory : String;
    documentsDirectory = paths[0] as String
    var fileManager: NSFileManager = NSFileManager()
    var fileList: NSArray = fileManager.contentsOfDirectoryAtPath(documentsDirectory, error: nil)!
    var filesStr: NSMutableString = NSMutableString(string: "Files in Documents folder \n")
    for s in fileList {
        filesStr.appendFormat("%@", s as String)
    }

    self.displayAlert(filesStr)
}

loadFileFromDocumentsFolder

func loadFileFromDocumentsFolder(fileName: String) {
    var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    var documentsDirectory : String;
    documentsDirectory = paths[0] as String
    var filePath: String = documentsDirectory.stringByAppendingPathComponent(fileName);
    var fileUrl: NSURL = NSURL(fileURLWithPath: filePath);
    self.handleDocumentOpenURL(fileUrl)

}

handleDocumentOpenUrl

func handleDocumentOpenURL(url: NSURL) {
    var requestObj = NSURLRequest(URL: url)
    webView.userInteractionEnabled = true
    webView.loadRequest(requestObj)
}

Hope this helps.

like image 93
euniceadu Avatar answered Nov 14 '22 12:11

euniceadu