Is there a way to include fields such as "BCC" and "CC" using NSSharingService? - swift

Im wondering if there is a way to compose an email in Swift and have it populate fields such as CC and BCC.
Currently I am using NSSharingService and it only appears to have the options for Recipient, Subject, and Body.
I'm not married to using NSSharingService, but I would like to know a way to implement what I am trying to do.
EDIT: I am developing for Mac and not iOS
class SendEmail: NSObject {
static func send(recipient: String) {
let service = NSSharingService(named:
service.recipients = ["Recipient Goes Here"]
service.subject = "Subject Goes Here"
service.perform(withItems: ["Body Goes Here"])
}
}

This works in Swift5 (Xcode 10.2.1, macOS 10.14.5)
let url = URL(string: "mailto:to#example.com?subject=subject&cc=cc#example.com&bcc=bcc#example.com")!
NSWorkspace.shared.open(url)

Related

How to print the current local network name in swift

I am creating an iOS app which displays the current local network name at the top of the screen, and so forth. I am trouble-shooting different ways to display this but I can't manage the current program. Can someone help me out?
I've looked at several GitHub, stack overflow, and youtube comments about this, but nome of them worked.
In the current Xcode I'm using which is Xcode(10.4.2) I'm using a label(correct me if I should use something else) to display the current Wifi named --> (WiFi: ......)
Please don't test on the simulator, use the iphone for testing.
Import SystemConfiguration :
import SystemConfiguration.CaptiveNetwork
In ViewDidLoad :
let wifiName = getWiFiName()
print("Wifi: \(String(describing: wifiName))")
Function :
func getWiFiName() -> String? {
var serviceSetIdentifier:String?
if let interfaces = CNCopySupportedInterfaces() as Array? {
interfaces.forEach { interface in
guard let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? else { return }
serviceSetIdentifier = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
}
}
return serviceSetIdentifier
}

Swift How do you edit the Metadata (ID3) of a .mp3 file in macOS

Swift How do you edit the Metadata (ID3) of a .mp3 file in macOS
I am writing a macOS app and have been trying for some while to change the wording in section of ‘More Info’ in an .mp3 and have done much searching of SO and found 2 snippets of code that will read the metadata but only one actually outputs the existing keys but I don’t understand how to write new data to any of them. I actually want to write data to a .mp3 file I have created and add an image if possible, as a newbie with some knowledge in Swift 3 can anybody help please. The output below is from a test song (Imagine_Test_Song) I have copied to my desktop.
I found this on SO Writing ID3 tags via AVMetaDataItem but I get a compiling error in these lines :-
soundFileMetadata.append(createMetadata(AVMetadataiTunesMetadataKeyArtist, "MyArtist")!) // compiler error here
soundFileMetadata.append(createMetadata(AVMetadataiTunesMetadataKeySongName, "MySong")!)
….
which says :- Missing argument label 'tagKey' in call. The func is this :-
func createMetadata(tagKey: String, _ tagValue: AnyObject?,
keySpace:String = AVMetadataKeySpaceiTunes) -> AVMutableMetadataItem? {
if let tagValue = tagValue {
let tag = AVMutableMetadataItem()
tag.keySpace = keySpace
tag.key = tagKey as NSCopying & NSObjectProtocol
tag.value = (tagValue as? String as! NSCopying & NSObjectProtocol) ?? (tagValue as? Int as! NSCopying & NSObjectProtocol)
return tag
}
return nil
}
Second snippet is my code below which does compile and outputs the various data but how do you edit the text and save the changes. Ideally I would also like to add “artwork” as well, is this possible?
let homeUrl = NSHomeDirectory()
let sourceFilePath = String(format: "%#/Desktop/%#.mp3", homeUrl, " Imagine_Test_Song")
let fileUrl = NSURL(fileURLWithPath: sourceFilePath)
var asset = AVAsset(url: fileUrl as URL) as AVAsset
//using the asset property to get the metadata of file
for metaDataItems in asset.commonMetadata {
//getting the title of the song
if metaDataItems.commonKey == "title" {
let titleData = metaDataItems.value as! NSString
print("title = \(titleData)")
}
//getting the "Artist of the mp3 file"
if metaDataItems.commonKey == "artist" {
let artistData = metaDataItems.value as! NSString
print("artist = \(artistData)")
}
//getting the "creator of the mp3 file"
if metaDataItems.commonKey == "creator" {
let creatorData = metaDataItems.value as! NSString
print("creator = \(creatorData)")
}
//getting the "Album of the mp3 file"
if metaDataItems.commonKey == "albumName" {
let albumNameData = metaDataItems.value as! NSString
print("albumName = \(albumNameData)")
}
Output :-
title = Imagine
creator = John Lennon
type = Singer-Songwriter
albumName = Imagine
Any help would be appreciated, thanks in advance.
After a lot of research on this issue, it seems the ability to modify and save AVMetaDataItems to an MP3 file is impossible using the AVFoundation API calls (even though the mp3 file type is listed as an option) due to licensing issues with MP3 files. So, the only way to do this, as far as I know, is to either roll your own id3 tag editor, or use a library/framework from another author.
I do not personally like using frameworks or libraries from other authors that do not provide the full source code because I have run into problems when the author stops maintaining the project and Apple changes something and the change breaks my apps.
However, I have found ID3TagEditor library by Fabrizio Duroni. Full source is available on github here. It's a straight forward and easy to use library. Fabrizio is actively maintaining the code as of this writing.

How to get e-mail subject from message:// URL in OSX Swift

I have a desktop app that receives e-mail URLs ("message://" scheme) from the drag&drop pasteboard and I want to get the Subject from the relevant message. The only clue I have, so far, is that the QuickLook library might give me an information object where I can retrieve this info from.
Since the QuickLook API seems to be rather in flux at the moment and most examples show how to use it in iOS, I simply cannot find a way to set up my "Preview" object using a URL and get the information from there.
I would like to avoid setting up my project as a QuickLook plugin, or setting up the whole preview pane / view scaffolding; at the moment I just want to get out what QuickLook loads before it starts displaying, but I can't comprehend what paradigm Apple wants me to implement here.
XCode 7.3.1.
It turns out I misinterpreted the contents of draggingInfo.draggingPasteboard().types as a hierarchical list containing only one type of info (URL in this case).
Had to subscribe to dragged event type kUTTypeMessage as String and retrieve the e-mail subject from the pasteboard with stringForType("public.url-name")
EDIT: Note that the current Mail.app will sometimes create a stack of mails when you drag an e-mail thread. Although the method above still works to get the subject of the stack, there is no URL in the dragging info then and since there's no list of Message-IDs available either, I had to resort to scraping the user's mbox directory:
// See if we can resolve e-mail message meta data
if let mboxPath = pboard.stringForType("com.apple.mail.PasteboardTypeMessageTransfer") {
if let automatorPlist = pboard.propertyListForType("com.apple.mail.PasteboardTypeAutomator") {
// Get the latest e-mail in the thread
if let maxID = (automatorPlist.allObjects.flatMap({ $0["id"]! }) as AnyObject).valueForKeyPath("#max.self") as? Int {
// Read its meta data in the background
let emailItem = draggingEmailItem
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// Find the e-mail file
if let path = Util.findEmlById(searchPath: mboxPath, id: maxID) {
// Read its contents
emailItem.properties = Util.metaDataFromEml(path)
dispatch_async(dispatch_get_main_queue(), {
// Update UI
});
}
}
}
}
}
Util funcs:
/* Searches the given path for <id>.eml[x] and returns its URL if found
*/
static func findEmlById(searchPath searchPath: String, id: Int)-> NSURL? {
let enumerator = NSFileManager.defaultManager().enumeratorAtPath(searchPath)
while let element = enumerator?.nextObject() as? NSString {
switch (element.lastPathComponent, element.pathExtension) {
case (let lpc, "emlx") where lpc.hasPrefix("\(id)"):
return NSURL(fileURLWithPath: searchPath).URLByAppendingPathComponent(element as String)!
case (let lpc, "eml") where lpc.hasPrefix("\(id)"):
return NSURL(fileURLWithPath: searchPath).URLByAppendingPathComponent(element as String)!
default: ()
}
}
return nil
}
/* Reads an eml[x] file and parses it, looking for e-mail meta data
*/
static func metaDataFromEml(path: NSURL)-> Dictionary<String, AnyObject> {
// TODO Support more fields
var properties: Dictionary<String, AnyObject> = [:]
do {
let emlxContent = try String(contentsOfURL: path, encoding: NSUTF8StringEncoding)
// Parse message ID from "...\nMessage-ID: <...>"
let messageIdStrMatches = emlxContent.regexMatches("[\\n\\r].*Message-ID:\\s*<([^\n\r]*)>")
if !messageIdStrMatches.isEmpty {
properties["messageId"] = messageIdStrMatches[0] as String
}
}
catch {
print("ERROR: Failed to open emlx file")
}
return properties
}
Note: If your app is sandboxed you will need the com.apple.security.temporary-exception.files.home-relative-path.read-only entitlement set to an array with one string in it: /Library/

Fetch an email body in mailcore2 OSX with swift

I try use this class: MCOIMAPFetchContentOperation for fetch body mail.
But i don't know how invoke her in swift and i don't know the arguments who are necessary.
Description of the class is: "This class implements an operation to fetch the content of a message. It can be a part or a full message."
Can you help me please !
Your question is a little vague but I assume to mean something like this :
func loadMsg(msg: MCOIMAPMessage, folder: String) {
let operation: MCOIMAPFetchContentOperation = session.fetchMessageByUIDOperationWithFolder(folder, uid: msg.uid)
operation.start { (error:NSError!, data:NSData!) -> Void in
let messageParser: MCOMessageParser = MCOMessageParser(data: data)
let msgHTMLBody: NSString = messageParser.htmlBodyRendering()
print ("HTML: \(msgHTMLBody)")
}
}

iPhone: Create Custom Field in contacts

i am developing a application in which i add contact to contact List. i am able to basic info like name, address, email, phone, notes etc. but i want to add some custom field like userLabel1, userValue1 , bioPersonal, bioWork, bioOther. so i want to add custom fields to address Book'contacts.
whether it is possible to add custom field to contact? if yes , then please suggest any link or sample code?
Basically, there is no way to do that. Address Book doesn't let you add custom fields. However, what you can do is put your data in the "Notes" field for each contact. That will, however, look weird in apps other than yours.
let store = CNContactStore()
// phoneNumberToEdit is the CNContact which you need to update
guard var mutableCont = phoneNumberToEdit?.mutableCopy() as? CNMutableContact else { return }
let phoneNumber = CNPhoneNumber(stringValue: "0123456789")
var currentContact = CNLabeledValue(label: "MyCustomLabel", value: phoneNumber)
mutableCont.phoneNumbers = [currentContact]
let request2 = CNSaveRequest()
request2.update(mutableCont)
do{
try store.execute(request2)
} catch let error{
print(error)
}