Email Account For MailCore2 - swift

I have created a Swift universal app that incorporates the MailCore2 API. It works perfectly on both debug and release mode. When I asked a friend in California to test it out, an alert view popped up with an error message. I found out that the reason for this was because I was using Google as the account I was emailing from.
Here is my code:
var smtpSession = MCOSMTPSession()
smtpSession.hostname = "smtp.gmail.com"
smtpSession.username = "matt#gmail.com"
smtpSession.password = "xxxxxxxxxxxxxxxx"
smtpSession.port = 465
smtpSession.authType = MCOAuthType.SASLPlain
smtpSession.connectionType = MCOConnectionType.TLS
smtpSession.connectionLogger = {(connectionID, type, data) in
if data != nil {
if let string = NSString(data: data, encoding: NSUTF8StringEncoding){
NSLog("Connectionlogger: \(string)")
}
}
}
var builder = MCOMessageBuilder()
builder.header.to = [MCOAddress(displayName: "Rool", mailbox: "itsrool#gmail.com")]
builder.header.from = MCOAddress(displayName: "Matt R", mailbox: "matt#gmail.com")
builder.header.subject = "My message"
builder.htmlBody = "Yo Rool, this is a test message!"
let rfc822Data = builder.data()
let sendOperation = smtpSession.sendOperationWithData(rfc822Data)
sendOperation.start { (error) -> Void in
if (error != nil) {
NSLog("Error sending email: \(error)")
} else {
NSLog("Successfully sent email!")
}
}
Google prevented the email from being sent because it thought a hijacker was trying to access my account (being that I am in a different state when I normally log in.)
My question is: Is there a way of preventing Google from blocking these emails from being sent? I would like people to be able to send emails, no matter where they are located. If this isn't possible, them is there an emailing service that doesn't prevent emails from being sent just because you (the users) are logging in from a different location?
Thanks in advance to all who reply.

this one works for me, hope it works for you too, try this,
let smtpSession:MCOSMTPSession = MCOSMTPSession()
smtpSession.hostname = "smtp.gmail.com"
smtpSession.port = 465
smtpSession.username = "abc#gmail.com"
smtpSession.password = "xxxxx"
smtpSession.authType = MCOAuthType.SASLPlain
smtpSession.connectionType = MCOConnectionType.TLS
let builder:MCOMessageBuilder = MCOMessageBuilder()
let from:MCOAddress = MCOAddress(displayName: "abc", mailbox: "abc#gmail.com")
let to:MCOAddress = MCOAddress(displayName: nil, mailbox: "abc#gmail.com")
builder.header.from = from
builder.header.to = [to]
builder.header.subject = "My Messgae"
builder.htmlBody = "This is test message"
let rcf822Data:NSData = builder.data()
let sendOperation:MCOSMTPSendOperation = smtpSession.sendOperationWithData(rcf822Data)
sendOperation.start { (error:NSError?) in
if (error != nil) {
print("Error Sending Mail : \(error)")
}else{
print("Mail Sent Successfully")
}
}

Related

Screen Sharing using Twilio in iOS

I am using Twilio iOS framework to connect in the group room.
On the click on connect room button below is the code which I used
let recorder = RPScreenRecorder.shared()
recorder.isMicrophoneEnabled = false
recorder.isCameraEnabled = false
// The source produces either downscaled buffers with smoother motion, or an HD screen recording.
videoSource = ReplayKitVideoSource(isScreencast: true, telecineOptions: ReplayKitVideoSource.TelecineOptions.disabled)
screenTrack = LocalVideoTrack(source: videoSource!,
enabled: true,
name: "Screen")
recorder.startCapture(handler: { (sampleBuffer, type, error) in
if error != nil {
print("Capture error: ", error as Any)
return
}
switch type {
case RPSampleBufferType.video:
self.videoSource?.processFrame(sampleBuffer: sampleBuffer)
break
case RPSampleBufferType.audioApp:
break
case RPSampleBufferType.audioMic:
// We use `TVIDefaultAudioDevice` to capture and playback audio for conferencing.
break
}
}) { (error) in
if error != nil {
print("Screen capture error: ", error as Any)
} else {
print("Screen capture started.")
}
}
if (accessToken == "TWILIO_ACCESS_TOKEN") {
do {
accessToken = try TokenUtils.fetchToken(url: tokenUrl)
} catch {
let message = "Failed to fetch access token"
logMessage(messageText: message)
return
}
}
// Prepare local media which we will share with Room Participants.
self.prepareLocalMedia()
// Preparing the connect options with the access token that we fetched (or hardcoded).
let connectOptions = ConnectOptions(token: accessToken) { (builder) in
// Use the local media that we prepared earlier.
builder.audioTracks = self.localAudioTrack != nil ? [self.localAudioTrack!] : [LocalAudioTrack]()
builder.videoTracks = self.localVideoTrack != nil ? [self.localVideoTrack!, self.screenTrack!] : [LocalVideoTrack]()
// Use the preferred audio codec
if let preferredAudioCodec = Settings.shared.audioCodec {
builder.preferredAudioCodecs = [preferredAudioCodec]
}
// Use the preferred video codec
if let preferredVideoCodec = Settings.shared.videoCodec {
builder.preferredVideoCodecs = [preferredVideoCodec]
}
// Use the preferred encoding parameters
if let encodingParameters = Settings.shared.getEncodingParameters() {
builder.encodingParameters = encodingParameters
}
// Use the preferred signaling region
if let signalingRegion = Settings.shared.signalingRegion {
builder.region = signalingRegion
}
builder.roomName = self.roomTextField.text
}
// Connect to the Room using the options we provided.
room = TwilioVideoSDK.connect(options: connectOptions, delegate: self)
logMessage(messageText: "Attempting to connect to room \(String(describing: self.roomTextField.text))")
When I connected in the group with remote participant I want to share the screen with remote participant.
To implement this feature I have referred the “ReplayKitExample” with in-app capture method. But not able to do that.
Remote participant not able to see the screen share content.
Nothing is happening related to screen share with this, and looking for inputs on implementing it.
I want to share the screen to remote participant.
Its happening because you are trying to send "cameraSource" and "videoSource" both data at the same time you have to unsubscribe the "cameraSource" before sending "viseoSource".
Heres my code you can refer:
//MARK: - Screen Sharing via replaykit
extension CallRoomViewController: RPScreenRecorderDelegate {
func broadCastButtonTapped(){
guard screenRecorder.isAvailable else {
print("Not able to Broadcast")
return
}
print("Can Broadcast")
if self.videoSource != nil {
self.stopConference()
} else {
self.startConference()
}
}
func publishVideoTrack(){
if let participant = self.room?.localParticipant,
let videoTrack = self.localVideoTrack {
participant.publishVideoTrack(videoTrack)
}
}
func unpublishVideoTrack(){
if let participant = self.room?.localParticipant,
let videoTrack = self.localVideoTrack {
participant.unpublishVideoTrack(videoTrack)
}
}
func stopConference() {
self.unpublishVideoTrack()
self.localVideoTrack = nil
self.videoSource = nil
self.localVideoTrack = LocalVideoTrack(source: cameraSource!, enabled: true, name: "Camera")
screenRecorder.stopCapture{ (captureError) in
if let error = captureError {
print("Screen capture stop error: ", error as Any)
} else {
print("Screen capture stopped.")
self.publishVideoTrack()
}
}
}
func startConference() {
self.unpublishVideoTrack()
self.localVideoTrack = nil
// We are only using ReplayKit to capture the screen.
// Use a LocalAudioTrack to capture the microphone for sharing audio in the room.
screenRecorder.isMicrophoneEnabled = false
// Use a LocalVideoTrack with a CameraSource to capture the camera for sharing camera video in the room.
screenRecorder.isCameraEnabled = false
// The source produces either downscaled buffers with smoother motion, or an HD screen recording.
self.videoSource = ReplayKitVideoSource(isScreencast: true,
telecineOptions: ReplayKitVideoSource.TelecineOptions.p60to24or25or30)
self.localVideoTrack = LocalVideoTrack(source: videoSource!,
enabled: true,
name: "Screen")
let videoCodec = Settings.shared.videoCodec ?? Vp8Codec()!
let (_, outputFormat) = ReplayKitVideoSource.getParametersForUseCase(codec: videoCodec,
isScreencast: true,
telecineOptions:ReplayKitVideoSource.TelecineOptions.p60to24or25or30)
self.videoSource?.requestOutputFormat(outputFormat)
screenRecorder.startCapture(handler: { (sampleBuffer, type, error) in
if error != nil {
print("Capture error: ", error as Any)
return
}
switch type {
case RPSampleBufferType.video:
self.videoSource?.processFrame(sampleBuffer: sampleBuffer)
break
case RPSampleBufferType.audioApp:
break
case RPSampleBufferType.audioMic:
// We use `TVIDefaultAudioDevice` to capture and playback audio for conferencing.
break
default:
print(error ?? "screenRecorder error")
}
}) { (error) in
if error != nil {
print("Screen capture error: ", error as Any)
} else {
print("Screen capture started.")
self.publishVideoTrack()
}
}
}
}
And you can connect room from viewDidLoad()
func connectToChatRoom(){
// Configure access token either from server or manually.
// If the default wasn't changed, try fetching from server.
accessToken = self.callRoomDetail.charRoomAccessToken
guard accessToken != "TWILIO_ACCESS_TOKEN" else {
let message = "Failed to fetch access token"
print( message)
return
}
// Prepare local media which we will share with Room Participants.
self.prepareLocalMedia()
// Preparing the connect options with the access token that we fetched (or hardcoded).
let connectOptions = ConnectOptions(token: accessToken) { (builder) in
// The name of the Room where the Client will attempt to connect to. Please note that if you pass an empty
// Room `name`, the Client will create one for you. You can get the name or sid from any connected Room.
builder.roomName = self.callRoomDetail.chatRoomName
// Use the local media that we prepared earlier.
if let audioTrack = self.localAudioTrack {
builder.audioTracks = [ audioTrack ]
}
if let videoTrack = self.localVideoTrack {
builder.videoTracks = [ videoTrack ]
}
// Use the preferred audio codec
if let preferredAudioCodec = Settings.shared.audioCodec {
builder.preferredAudioCodecs = [preferredAudioCodec]
}
// Use the preferred video codec
if let preferredVideoCodec = Settings.shared.videoCodec {
builder.preferredVideoCodecs = [preferredVideoCodec]
}
// Use the preferred encoding parameters
let videoCodec = Settings.shared.videoCodec ?? Vp8Codec()!
let (encodingParams, _) = ReplayKitVideoSource.getParametersForUseCase(codec: videoCodec,
isScreencast: true,
telecineOptions:ReplayKitVideoSource.TelecineOptions.p60to24or25or30)
builder.encodingParameters = encodingParams
// Use the preferred signaling region
if let signalingRegion = Settings.shared.signalingRegion {
builder.region = signalingRegion
}
builder.isAutomaticSubscriptionEnabled = true
builder.isNetworkQualityEnabled = true
builder.networkQualityConfiguration = NetworkQualityConfiguration(localVerbosity: .minimal,
remoteVerbosity: .minimal)
}
// Connect to the Room using the options we provided.
room = TwilioVideoSDK.connect(options: connectOptions, delegate: self)
print( "Attempting to connect to room \(self.callRoomDetail.chatRoomName ?? ""))")
self.showRoomUI(inRoom: true)
}
You can get ReplayKitVideoSource file and other files from twilio repository https://github.com/twilio/video-quickstart-ios/tree/master/ReplayKitExample
I work at Twilio and I can confirm that you should be able to publish video tracks for both camera and screen at the same time without issue.
It is difficult to identify why this is not working for you without a completely functional example app.
However I have tested this using one of our reference apps and confirmed it is working. More details are here: https://github.com/twilio/video-quickstart-ios/issues/650#issuecomment-1178232542
Hopefully this is a useful example for how to publish both camera and screen video at the same time.

skpsmtpmessage sending email function is not working correctly?

So I downloaded the skpsmtpmessage pod and installed it to my project. I have a file called MailSender in the project that looks like:
import Foundation
import skpsmtpmessage
class MailSender: NSObject, SKPSMTPMessageDelegate {
static let shared = MailSender()
func sendEmail() {
let message = SKPSMTPMessage()
message.relayHost = "smtp.gmail.com"
message.login = "myemail#gmail.com"
message.pass = "password"
message.requiresAuth = true
message.wantsSecure = true
message.relayPorts = [587]
message.fromEmail = "myemail#gmail.com"
message.toEmail = "recipientemail#gmail.com"
message.subject = "subject"
let messagePart = [kSKPSMTPPartContentTypeKey: "text/plain; charset=UTF-8", kSKPSMTPPartMessageKey: "body of email"]
message.parts = [messagePart]
message.delegate = self
message.send()
}
func messageSent(_ message: SKPSMTPMessage!) {
print("Successfully sent email!")
}
func messageFailed(_ message: SKPSMTPMessage!, error: Error!) {
print("Sending email failed!")
}
}
In ContentView, I have a button that looks like:
Button("click me") {
MailSender.shared.sendEmail()
}
When I run the simulator and click the button in ContentView, I get a bunch of "*** stopping watchdog ***" messages in the output and then some additional messages that say "S: 250-smtp.gmail.com at your service, [My IP Address]", and then there's a message that says "S: 535-5.7.8 Username and Password not accepted. Learn more at", but I know that the from email and password that I'm providing are correct (it's my personal email information in my version of the project). Any help would be greatly appreciated.
By default support for external clients is off on Gmail, so login in your account and make sure you turned on some, IMAP is preferred.
Then make sure you configure properly email client

CKSubscription error iOS10

My subscriptions were working properly with iOS 9, but since I updated, I have a very odd error. I have two subscription methods that are equal, except for the fields they manage. Here is the code:
let meetingSubscriptionPredicate = Predicate(format: "Users CONTAINS %#", (id?.recordName)!)
let meetingSubscription = CKQuerySubscription(recordType: "Meetings", predicate: meetingSubscriptionPredicate, options: .firesOnRecordCreation)
let notification = CKNotificationInfo()
notification.alertBody = "Meeting Created!"
notification.shouldBadge = true
notification.accessibilityPerformEscape()
meetingSubscription.notificationInfo = notification
database.save(meetingSubscription) { (result, error) -> Void in
if error != nil {
print(error!.localizedDescription)
}
}
let universitiesSubscriptionPredicate = Predicate(format: "Name = %#", self.UniversityTextField.text!)
let universitiesSubscription = CKQuerySubscription(recordType: "Universities", predicate: universitiesSubscriptionPredicate, options: .firesOnRecordCreation)
let universitiesNotification = CKNotificationInfo()
universitiesNotification.alertBody = "Your university is now on Meet'em!"
universitiesNotification.shouldBadge = true
universitiesNotification.accessibilityPerformEscape()
universitiesSubscription.notificationInfo = universitiesNotification
database.save(universitiesSubscription, completionHandler: { (saved, error) in
if error != nil {
print(error!.localizedDescription)
}
else {
print("University subscription created")
}
})
The odd thing is that the Meeting subscription is saved, and the University's subscription is not. I've double checked the names and they are all right at the Dashboard. Besides that, I'm not getting any notification on my phone when supposed to...
Found elsewhere online that you can try to reset your development environment. In my case, the predicate I was trying to use was not set to queryable. This is ticked where you define your record type. The reason it worked one day and not another is possibly due to moving from development to production. At that time you are asked to optimize indexes, and it is possibly here that the ability to search on a given predicate is dropped. That seemed to be the case for me anyway.

SWIFT: do I have someone set a record with different text every time?

So I made a chatroom and when someone sends a message they also add a Subscription in my cloud kit database but the problem is there cant be more then one of the same name that is a subscription and I want them to be able to set more subscriptions then one. Here is some code:
func setupCloudKitSubscription () {
let userDefaults = NSUserDefaults.standardUserDefaults()
if userDefaults.boolForKey("subscribed") == false {
let predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
let subscription = CKSubscription(recordType: "Extra1", predicate: predicate, options: CKSubscriptionOptions.FiresOnRecordCreation)
let notificationInfo = CKNotificationInfo()
notificationInfo.alertLocalizationKey = "New Sweet"
notificationInfo.shouldBadge = true
subscription.notificationInfo = notificationInfo
let publicData = CKContainer.defaultContainer().publicCloudDatabase
publicData.saveSubscription(subscription) { (subscription:CKSubscription?, error:NSError?) -> Void in
if error != nil {
print(error?.localizedDescription)
}else{
userDefaults.setBool(true, forKey: "subscribed")
userDefaults.synchronize()
You see how it says recordType: "Extra1" how can I made the "Extra1" different text every time someone makes a subscription? Thanks!
Your question is not completely clear. I think what you wanted to ask is that you want the subscription to send you a different message with each notification.
You could set it to display one or more fields of the record. For doing that you should use something like this:
notificationInfo.alertLocalizationKey = "Response: %1$#"
notificationInfo.alertLocalizationArgs = ["responseField"]
Then you also need this in your Localization.Strings file.
"Response: %1$#" = "Response: %1$#";

Quickblox, chat room does not sends push notification

I created a chat room in Quickblox, when i sends message to chatroom its offline users does not get any push notification.
To send message :
[[QBChat instance] sendMessage:#"Hey! Did you see last Liverpool match?" toRoom:liverpoolFansRoom];
Is there anything that i am doing wrong or its not enabled on Quickbolx server to sends notification on chatroom's offline users.
Thanx
Push messages does not sends automatically. If you know your recipient user's ID you can send push message manually - you should call method provided below:
[QBMessages TSendPushWithText:#"text"
toUsers:(int)userId
delegate:nil];
Swift 3 :
You can send push notifications for all user connected with the dialog using following code:
var payload = [String:String]()
payload["message"] = message.text!
payload["dialog_id"] = self.dialog.id!
do {
let data = try JSONSerialization.data(withJSONObject: payload, options: .prettyPrinted)
let message = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
var opponentIDs: [String] = []
for userId in self.dialog.occupantIDs! {
// Discard currently logged in user
if userId.uintValue != _user.id {
opponentIDs.append(String(describing: userId))
}
}
let event = QBMEvent()
event.message = message
event.usersIDs = opponentIDs.joined(separator: ",")
event.notificationType = QBMNotificationType.push
event.type = QBMEventType.oneShot
QBRequest.createEvent(event, successBlock: { (response, arrEvents) in
kprint(items: event.name ?? "")
}, errorBlock: { (errRes) in
kprint(items: errRes.error?.description ?? "")
})
} catch {
print(error.localizedDescription)
}