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)")
}
}
Related
I am using MessageKit to make a basic chatting app. However, I wanted to do something with the text of the latest sent message.
This is an example of what I want:
print("This is what I was talking about:\n\n", newMessage.kind)
I get:
text("Hi StackOverflow!")
However, I wish to get only this String "Hi StackOverflow". Any help would be appreciated thanks.
You can use a switch statement. For example,
var message = ""
switch newMessage.kind {
case .text(let messageText):
message = messageText
default:
break
}
This question is similar to yours, and may be useful
func getTheMessageText(messageKind: MessageKind) -> String {
if case .text(let value) = messageKind {
return value
}
return ""
}
Usage: Call this method to get the message as a string like
let messageType:MessageType = messageList[indexPath.section]
getTheMessageText(messageKind: messageType.kind)
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
}
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)
I am developing a iOS app in swift that uses Core Data. I am trying to implement some Core Data validation. I don't have any custom logic yet, so I am using the "Class definition" setting in the model to make Xcode create the NSManagedObject subclasses automatically. In this case, according to the documentation, I can put my validation logic in an extension. My code looks like this:
extension Person {
func validateEmail(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws {
var error: NSError? = nil
if let email = value.pointee as? String {
let regex = "^.+#([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$"
let predicate = NSPredicate(format: "SELF MATCHES %#", regex)
if !predicate.evaluate(with: email) {
let errorType = UserErrorType.invalidEmail
error = NSError(domain: errorDomain, code: errorType.rawValue, userInfo: [ NSLocalizedDescriptionKey : "The email address is invalid." ] )
}
} else {
let errorType = UserErrorType.invalidEmail
error = NSError(domain: errorDomain, code: errorType.rawValue, userInfo: [ NSLocalizedDescriptionKey : "The email address is invalid." ] )
}
if let error = error {
throw error
}
}
Unfortunately, my validation code does never get called. I know it gets called only when actually saving the context, but it is never called. I am also trying:
let entity = NSEntityDescription.entity(forEntityName: "Person", in: self.persistentContainer.viewContext)
let person = NSManagedObject(entity: entity!, insertInto: self.persistentContainer.viewContext) as! Person
person.age = 16
person.hasDrivingLicense = true
person.email = "novalidemail"
do {
try person.validateForInsert()
} catch {
let validationError = error as NSError
print(validationError)
}
But my validation method does never get called. Another test I made was to override validateValue like this in the extension:
public override func validateValue(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>, forKey key: String) throws {
print("\(key)")
}
This last method instead gets called for all keys, including the "email" key I am after.
I finally found the issue. Prefixing #objc to the validation function made it work, so it gets called. So, instead of:
func validateEmail(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws {}
Just:
#objc func validateEmail(_ value: AutoreleasingUnsafeMutablePointer<AnyObject?>) throws {}
I had not tried this yet because, in this project coming from a tutorial, the validation functions do not have an #objc prefix and still they are called. I would like to understand the difference and discover why I need that prefix in my project. Thanks
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/