How to Integrate iTunes File Sharing Features Within Your iPhone and iPad Apps (In a Brilliant Way!)

0
Shares
How to Integrate iTunes File Sharing Features Within Your iPhone and iPad Apps (In a Brilliant Way!)
5 (100%) 1 vote

Previously, before the release of iTunes 9.1, users were not able to transfer files between their app and computer. And, due to lack of this, they added new iTunes file sharing feature with the new release of iTunes 9.1, which provides a great and convenient way of sharing files between your computer and your app.

However, understanding what exactly you need to do for getting this to work in the real-world scenario can be a bit tricky. So, we thought that it would be a good idea to write an iTunes tutorial that includes how to enable iTunes file sharing feature so that you can transfer files between your app and your computer, step by step!

First of all, let’s start with a basic overview of how file sharing iPhone exactly works?

To enable the file sharing iTunes feature in your app, you just simply need to add key: “Application supports iTunes file sharing” Value:“YES” in “info.plist”

iTunes File Sharing (1)

By doing this, iTunes will display all files that you save to documents directory in your iOS app to the user, when the user goes to “Apps” page in iTunes and scrolls down to the bottom.

So, now that you know how to enable the feature, let’s go forward and understand how to integrate this feature in your own app.

Code Steps!

1. Get Array for store listing of document directory contents and outlet of tableview.

//Decalir IB
@IBOutlet var tblList: UITableView?

//Declair Variables
var arrAllFiles = [String]()

2. Fetch Content from Document directory

func loadDataFromDocumentDirectory() { //Get All Files from Document Directory to Array arrAllFiles = listFilesFromDocumentsFolder() tblList?.reloadData() } //MARK:- Get List of document from document directory func listFilesFromDocumentsFolder() -> [String] { let dirs = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) if dirs.count != 0 { let dir = dirs[0] let fileList = try! NSFileManager.defaultManager().contentsOfDirectoryAtPath(dir) return fileList // edit: added ! for Swift 1.2 compatibitily }else{ let fileList = [“No Any File Found.”] return fileList } }

3. Call “loadDataFromDocumentDirectory” from “viewDidLoad”

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.loadDataFromDocumentDirectory()
}

4. It will show all the file names in table list by given below code

//MARK: UITableViewDelegate
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 44
}

//MARK: UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1;
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrAllFiles.count;
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
configureCell(cell, forRowAtIndexPath: indexPath)
return cell
}

func configureCell(cell: UITableViewCell, forRowAtIndexPath: NSIndexPath) {
cell.textLabel?.text = arrAllFiles[forRowAtIndexPath.row];
}

5. We can check this functionality by adding image from iPhone gallery to document directory

// MARK: - UIImagePickerController Get Image from Gallary Methods
//For Delegate self add UIImagePickerControllerDelegate, UINavigationControllerDelegate
@IBAction func getImageFromGallary() {
let imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true;
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.delegate = self
presentViewController(imagePicker, animated: true, completion: nil)
}


// MARK: - UIImagePickerControllerDelegate Methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let dictPicker:Dictionary = info;
print(dictPicker)

var newImage: UIImage
let imageURL = info[UIImagePickerControllerReferenceURL] as! NSURL
let result = PHAsset.fetchAssetsWithALAssetURLs([imageURL], options: nil)
let filename = (result.firstObject?.filename)! as String

//Create path for save image in document directory
let localPath = self.pathToDocsFolder(filename)

if let possibleImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
newImage = possibleImage
} else if let possibleImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
newImage = possibleImage
} else {
return
}

let data = UIImagePNGRepresentation(newImage)
data!.writeToFile(localPath, atomically: true)

dismissViewControllerAnimated(true) {
//Reload tableview
self.loadDataFromDocumentDirectory()
}
}

func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
dismissViewControllerAnimated(true, completion: nil)
}


//MARK:- Get path of document directory
func pathToDocsFolder(fileName:String) -> String {
let pathToDocumentsFolder = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
return pathToDocumentsFolder.stringByAppendingString("/\(fileName)")
}

6. For remove data from document directory

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == UITableViewCellEditingStyle.Delete {
self.removeOldFileIfExist(arrAllFiles[indexPath.row])
arrAllFiles.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}


//MARK:- Remove document from document directory
func removeOldFileIfExist(fileName:String) {
let filePath = self.pathToDocsFolder(fileName)
if NSFileManager.defaultManager().fileExistsAtPath(filePath) {
do {
try NSFileManager.defaultManager().removeItemAtPath(filePath)
} catch {
print("an error during a removing")
}
}
}

Here, you can check your application files as shown in below image.

FileSharing2

There you go! By adding the above code you can now easily add file sharing feature in your own app. And, if you’ve any question related to this tutorial you can ask our development team for the solution. You can also hire iPhone app developer from Space-O technologies for your next project.

Also, if you need a copy of this tutorial, you can grab it here.

 
0
Shares
 

LET'S TALK VALIDATE YOUR IDEA!