How can I save a CKAsset in Swift 2? - swift2

Swift 2
I am trying to save a small asset to CloudKit but not having much luck finding example code. The record is "Table1" and the asset is in the application bundle. Any tips would be helpful. iOS9 Swift 2.
let audioPath = NSBundle.mainBundle().pathForResource("song-1", ofType: "mp3")!
let itemRecord:CKRecord = CKRecord(recordType: "Table1")
db.saveRecord(itemRecord) { (record:CKRecord?, error:NSError?) -> Void in

You first have to create a CKAsset object. You could do that with something like:
let audioPath = NSBundle.mainBundle().pathForResource("song-1", ofType: "mp3")!
var file: CKAsset? = CKAsset(fileURL: NSURL(fileURLWithPath: audioPath))
After that you can just add it to your CKRecord using:
itemRecord.setValue(file, forKey: "AudioFile")

Related

Swift 2 - Share video with UIActivityViewController

I am trying to share a video from a URL using UIActivityViewController.
If I try with an Image I have not problems.
Share Image Works:
let imageThump = NSURL(string: "https://example.com/image.png")
let imageData = NSData(contentsOfURL: imageThump!)
let objectsToShare = [comment!, imageData!]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
Share Video is not working. Why?
let videoShare = NSURL(string: "https://example.com/video.mp4")
let videoData = NSData(contentsOfURL: videoShare!)
let objectsToShare = [comment!, videoData!]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
THIS IS HOW YOU DO IT ...
guard let urlData = NSData(contentsOfURL: NSURL(string:"https://example.com/video.mov)")!) else {
return
}
print(urlData)
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let docDirectory = paths[0]
let filePath = "\(docDirectory)/tmpVideo.mov"
urlData?.writeToFile(filePath, atomically: true)
// File Saved
let videoLink = NSURL(fileURLWithPath: filePath)
let objectsToShare = [videoLink] //comment!, imageData!, myWebsite!]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
activityVC.setValue("Video", forKey: "subject")
// New Excluded Activities Code
if #available(iOS 9.0, *) {
activityVC.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList, UIActivityTypeAssignToContact, UIActivityTypeCopyToPasteboard, UIActivityTypeMail, UIActivityTypeMessage, UIActivityTypeOpenInIBooks, UIActivityTypePostToTencentWeibo, UIActivityTypePostToVimeo, UIActivityTypePostToWeibo, UIActivityTypePrint]
} else {
// Fallback on earlier versions
activityVC.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList, UIActivityTypeAssignToContact, UIActivityTypeCopyToPasteboard, UIActivityTypeMail, UIActivityTypeMessage, UIActivityTypePostToTencentWeibo, UIActivityTypePostToVimeo, UIActivityTypePostToWeibo, UIActivityTypePrint ]
}
self.presentViewController(activityVC, animated: true, completion: nil)
Remember that a video is usually a big file, so it'll take some time for it to be downloaded and saved. Here I used part of the first answer but adding some GCD. You'll get better results.
This is how I did it to avoid the App to stay frozen until the video is downloaded and saved:
let url = NSURL(string: "https://example.com/video.mov")
//Show activity indicator
DispatchQueue.global(qos: .background).async {
guard let urlData = NSData(contentsOf: url) else { return }
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let filePath="\(documentsPath)/tempFile.mov"
DispatchQueue.main.async {
urlData.write(toFile: filePath, atomically: true)
//Hide activity indicator
let activityVC = UIActivityViewController(activityItems: [NSURL(fileURLWithPath: filePath)], applicationActivities: nil)
activityVC.excludedActivityTypes = [.addToReadingList, .assignToContact]
self.present(activityVC, animated: true, completion: nil)
}
}
It is not working because this class does not allow NSData to be passed to the Facebook activity type.
"UIActivityTypePostToFacebook
The object posts the provided content to the user’s wall on Facebook.
When using this service, you can provide NSString, NSAttributedString, UIImage, ALAsset, and NSURL objects as data for the activity items. You may also specify NSURL objects whose contents use the assets-library scheme."
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIActivity_Class/index.html#//apple_ref/doc/constant_group/Built_in_Activity_Types
I have been trying to get this to work as well. Haven't figured out how to get it to work; however, this is why your code is not working.

Cannot invoke initializer for type 'AVPlayer'

I'm having an issue getting my video to play via AVPlayer. For some reason I'm getting the error 'Cannot invoke initializer for type 'AVPlayer' with an argument list of type '(URL:NSURL)'
The weird thing is, this exact code snippet works in another one of my projects. I do have the AVKit and AVFoundation frameworks imported.
Well, I realized my dumb mistake. I had a local variable (player), so it died instantly before it could even play. I moved it up a level to be an instance variable so it persists as long as the view controller persists.
var MoviePlaying:Bool = false
let path = NSBundle.mainBundle().pathForResource("big_buck_bunny_720p_50mb", ofType:"mp4")
var player: AVPlayer = AVPlayer()
let playerController = AVPlayerViewController()
#IBAction func PlayTapped(sender: UIButton) {
let moviePlayerController = AVPlayerViewController()
let path = NSBundle.mainBundle().pathForResource("big_buck_bunny_720p_50mb", ofType:"mp4")
let url = NSURL.fileURLWithPath(path!)
let playerVC = AVPlayerViewController()
var player: AVPlayer = AVPlayer()
playerVC.player = AVPlayer(URL: url)
self.presentViewController(playerVC, animated: true, completion: nil)

Simple Swift file download with URL

So I have the URL as string (in this case a JPG but would like a general procedure for any file type if possible) and I have the file path as string where I want to save the file.
What would be the fastest way to get this implemented?
Please keep in mind this is for OSX command line application. I tried few sample codes found here, mostly using UIImage but I get error:"Use of unresolved identifier", adding "import UIKit" gets me error:"No such Module". Please help!
import Foundation
let myURLstring = "http://www.safety.vanderbilt.edu/images/staff/Bob-Wheaton.jpg"
let myFilePathString = "/Volumes/HD/Staff Pictures/Bob-VEHS.jpg"
---> ABOVE IS THE ORIGINAL QUESTION <---
---> BELOW IS NEW IMPROVED CODE: WORKING <---
import Foundation
let myURLstring = "http://www.safety.vanderbilt.edu/images/staff/Bob-Wheaton.jpg"
let myFilePathString = "/Volumes/HD/Staff Pictures/Bob-VEHS.jpg"
let url = NSURL(string: myURLstring)
let imageDataFromURL = NSData(contentsOfURL: url)
let fileManager = NSFileManager.defaultManager()
fileManager.createFileAtPath(myFilePathString, contents: imageDataFromURL, attributes: nil)
If you're writing for OS X, you'll use NSImage instead of UIImage. You'll need import Cocoa for that - UIKit is for iOS, Cocoa is for the Mac.
NSData has an initializer that takes a NSURL, and another that takes a file path, so you can load the data either way.
if let url = NSURL(string: myURLstring) {
let imageDataFromURL = NSData(contentsOfURL: url)
}
let imageDataFromFile = NSData(contentsOfFile: myFilePathString)
With Swift 4, the code will be:
if let url = URL(string: myURLstring) {
let imageDataFromURL = try Data(contentsOf: url)
}

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
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.

CoreData auto-generated swift code error

I'm new to swift and core data. I've created a simple OS X application using core data. So in the AppDelegate.swift there is a lot of auto-generated code. I just want to save name and lastname when I press a button in the MainMenu.xib I've been searching around for a while on how to use core data in a OS X application using swift but with no success.
This is my code:
#IBAction func buttonAggiungiNewDipendentePressed(sender : AnyObject) {
println("Button pressed from popover");
//var AppDel:AppDelegate = (NSApplication.sharedApplication().delegate as AppDelegate)
let context = self.managedObjectContext!
var nome = popAggiungiDipendenteNome.stringValue;
var cognome = popAggiungiDipendenteCognome.stringValue;
var newUser = NSEntityDescription.insertNewObjectForEntityForName("Dipendenti", inManagedObjectContext: context) as NSManagedObject
newUser.setValue(nome, forKey: "nome")
newUser.setValue(cognome, forKey: "cognome")
context.save(nil)
popover.performClose(true);
}
I'm getting the following crash: Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP,subcode=0x0) inside the auto generate code in AppDelegate.swift:
var managedObjectModel: NSManagedObjectModel? {
// Creates if necessary and returns the managed object model for the application.
if let mom = _managedObjectModel {
return mom
}
let modelURL = NSBundle.mainBundle().URLForResource("ElencoTelefonicoAkhela2", withExtension: "momd")
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)
return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil
When it tries to return the managedObjectModel. Any idea? Thanx in advance
instead of insertNewObjectForEntityForName use:
let en = NSEntityDescription.entityForName("Photo", inManagedObjectContext: context)
let photo:Photo = Photo(entity:en, insertIntoManagedObjectContext:context)

Resources