AVSpeechSynthesizer delegate method didStartSpeechUtterance not being called - ios7

I am having trouble wth AVSpeechSynthesizer and utterances (ios 7.1.1)
The AVSpeechSynthesizer is initialised in a handler class with the delegate as self:
self.synthesizer = [[AVSpeechSynthesizer alloc] init];
self.synthesizer.delegate = self;
I have the following methods implemented in the delegate:
-(void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance {
NSLog(#"Finish");
}
-(void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didStartSpeechUtterance:(AVSpeechUtterance *)utterance{
NSLog(#"Start");
}
and my speech is called via this method:
- (void)speak:(NSString *)spokenWord{
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:spokenWord];
[self.synthesizer speakUtterance:utterance];
}
I then call the method repeatedly e.g.
[AVhandler speak:_word];
[AVhandler speak:_word];
[AVhandler speak:_word];
I would expect to see in the log:
Start
Finish
Start
Finish
Start
Finish etc
But instead I see:
Start
Finish
Finish
Finish
Finish
Why is the didStartSpeechUtterance not being called?
Thanks.

Answer is a little late, apologies. To resolve this, also put:
synthesizer.delegate = self;
in the -(void) as below
- (void)speak:(NSString *)spokenWord{
AVSpeechUtterance *utterance = [[AVSpeechUtterance alloc] initWithString:spokenWord];
[self.synthesizer speakUtterance:utterance];
synthesizer.delegate = self;
}
and in the didFinish as below:
-(void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance {
NSLog(#"Finish");
synthesizer.delegate = self;
}

Also don't forget to add a reference to the AVSpeechSynthesizerDelegate Protocol in your .h file, such as:
#interface ViewController : UIViewController <AVSpeechSynthesizerDelegate>
Then you can put your synthesizer.delegate = self; in your ViewDidLoad method only.
Hope it helps.

Related

Open ears text to speech (voice) not working when getting string from another class/controller (IOS, Objective c)

I am very new to objective c and OpenEars so please forgive me if I have some messy code and if I am lost in very simple problem.
Anyhow, I have two controllers in this application. The first being the default ViewController and the second one being a new one that I made called ReplyManagerController.
The code in the ViewController basically uses the one in the tutorial with some (maybe more some) changes.
EDIT:
The app is supposed to be a basic app where a user says something and the app replies.
But the original problem was that I could not get the string to display or TTS to work when my ViewController got it's string from another class/controller.
The answer in my below mentions that it was probably because my other class was calling my ViewController without the self.fliteController initialized.
How would I initialize the ViewController with self.fliteController initialized?
ViewController.m
- (void) pocketsphinxDidReceiveHypothesis:(NSString *)hypothesis recognitionScore:(NSString *)recognitionScore utteranceID:(NSString *)utteranceID {
NSString *strResult = hypothesis; //speech to text to string
ReplyManager* replyObject = [[ReplyManager alloc] init];
[replyObject speechResult:(NSString*)strResult viewController:self];
}
- (void) getReply:(NSString*)replyStr{
[self.fliteController say:replyStr withVoice:self.slt];
[self updateText:replyStr];
}
- (IBAction)updateText:(NSString*)replyStr{
labelOne.text = replyStr;
labelOne.adjustsFontSizeToFitWidth = YES;
labelOne.minimumFontSize = 0;
}
Any help will be great! Thanks!
ReplyManager.m
- (void) speechResult:(NSString*)strResult {
NSString *replystr;
NSString *greetings = #"Hi!";
NSString *sorry = #"Sorry I didn't catch that?";
ViewController* getReply = [[ViewController alloc] init];
if ([strResult isEqualToString:#"HELLO"])
{
replystr = greetings;
[getReply getReply:(NSString*)replystr];
}
else
{
replystr = sorry;
[getReply getReply:(NSString*)replystr];
}
}
EDIT 2:
viewDidLoad Method
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.fliteController = [[OEFliteController alloc] init];
self.slt = [[Slt alloc] init];
self.openEarsEventsObserver = [[OEEventsObserver alloc] init];
[self.openEarsEventsObserver setDelegate:self];
}
ViewController* getReply = [[ViewController alloc] init];
Here you init a new ViewController which does not have self.fliteController defined most likely. You need to reuse previos controller, for example like this:
[replyObject speechResult:(NSString*)strResult viewController:self];
So you can use already initialized viewController later. Overall it is better to initialize objects like viewController or replyController beforehand, not inside callback methods.
It sounds like a timing issue where you're trying to use fliteController before it's been initialized.
In your ViewController class, where do you assign a value to the fliteController property? In an initializer? -(void)viewDidLoad?
In ReplyManagerController add:
ViewController* getReply = [[ViewController alloc] init];
// Add these lines
NSLog(getReply.fliteController); // Is this nil?
[getReply.view layoutIfNeeded];
NSLog(getReply.fliteController); // Is it still nil?
Does the above fix the problem? If so, you're probably initializing fliteController in -(void)viewDidLoad. What's the result of the two NSLog statements?

CNUI ERROR Selection predicates are set but the delegate does not implement contactPicker:didSelectContact:

I try to use the new iOS 9.0 CNContactPickerViewController to select a contact in objective-C. I set the delegate and implement the CNContactPickerDelegate methods.
#import ContactsUI;
#import Contacts;
//-----------------------------------------------------------------------
- (void) presentContacts
{
CNContactPickerViewController *contactPicker = [[CNContactPickerViewController alloc] init];
contactPicker.delegate = self;
contactPicker.predicateForEnablingContact = [NSPredicate predicateWithFormat:#"familyName LIKE[cd] 'smith'"];
contactPicker.predicateForSelectionOfContact = [NSPredicate predicateWithFormat:#"TRUEPREDICATE"];
[_myViewController presentViewController:contactPicker animated:YES completion:nil];
}
//-----------------------------------------------------------------------
- (void) contactPickerDidCancel: (CNContactPickerViewController *) picker
{
NSLog(#"didCancel");
}
//-----------------------------------------------------------------------
- (void) contactPicker: (CNContactPickerViewController *) picker
didSelectContact: (CNContact *) contact
{
NSLog(#"didSelectContact"):
}
//-----------------------------------------------------------------------
- (void) contactPicker: (CNContactPickerViewController *) picker
didSelectContactProperty: (CNContactProperty *) contactProperty
{
NSLog(#"didSelectProperty");
}
//-----------------------------------------------------------------------
The contacts picker is presented with 'smith' selectable but I get the following message:
[CNUI ERROR] Selection predicates are set but the delegate does not implement contactPicker:didSelectContact: and contactPicker:didSelectContactProperty:. Those predicates will be ignored.
And I never get any log from the delegate methods. It behaves exactly as the line
contactPicker.delegate = self;
is ignored. Even I click on the "cancel" button in the picker, I don't get my "didCancel" message but I get another message:
plugin com.apple.MobileAddressBook.ContactsViewService invalidated
I found in https://forums.developer.apple.com/thread/12275 somebody with the similar problem in swift and he solved it telling us: "So I found that the ContactsPicker I was calling was in the wrong module" but I do not understand how we can get the wrong module and how to call the "right" module.
I have the same problem on the simulator and on a real device (iPad).
Thanks to Joel in my related question With CNContactPickerViewController in iOS 9.0, how to enable/disable single or multiple selection?, I found that I just forgot to store the CNContactPickerViewController in a property that exists the time the user make the selection.
So my code becomes:
- (void) presentContacts
{
_contactPicker = [[CNContactPickerViewController alloc] init];
contactPicker.delegate = self;
...
}

MultipeerConnectivity Session management

I am really stuck at the moment trying to get the grasp of invites in the MultipeerConnectivityFramework.
Right now I have an ipad App acting as the Advertiser and an iphone App acting as Browser.
I have implemented a sharedService for the MultipeerFramework and did the following:
Advertiser
#implementation MultipeerConnectivityService {
MCNearbyServiceAdvertiser *_advertiser;
MCSession *_session;
MCNearbyServiceBrowser *_browser;
}
- (void)automaticAdvertiseWithName:(NSString *)name {
MCPeerID *peerID = [[MCPeerID alloc] initWithDisplayName:name];
_session = [[MCSession alloc] initWithPeer:peerID];
_session.delegate = self;
_advertiser = [[MCNearbyServiceAdvertiser alloc] initWithPeer:peerID discoveryInfo:nil serviceType:kServiceType];
_advertiser.delegate = self;
[_advertiser startAdvertisingPeer];
}
- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didReceiveInvitationFromPeer:(MCPeerID *)peerID withContext:(NSData *)context invitationHandler:(void (^)(BOOL, MCSession *))invitationHandler {
invitationHandler([#YES boolValue], _session);
NSLog(#"Invitation accepted");
}
Browser
- (void)automaticBrowsingWithName:(NSString *)name {
MCPeerID *peerID = [[MCPeerID alloc] initWithDisplayName:name];
_browser = [[MCNearbyServiceBrowser alloc] initWithPeer:peerID serviceType:kServiceType];
_browser.delegate = self;
[_browser startBrowsingForPeers];
}
- (void)browser:(MCNearbyServiceBrowser *)browser didNotStartBrowsingForPeers:(NSError *)error {
if ([_delegate respondsToSelector:#selector(browser:didNotStartBrowsingForPeers:)]) {
[_delegate browserDidNotStartBrowsingForPeers];
}
}
- (void)browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID withDiscoveryInfo:(NSDictionary *)info {
[browser invitePeer:peerID toSession:[self getMCSession] withContext:nil timeout:10];
if ([_delegate respondsToSelector:#selector(browser:foundPeer:)]) {
[_delegate browser:browser foundPeer:peerID];
}
}
- (void)browser:(MCNearbyServiceBrowser *)browser lostPeer:(MCPeerID *)peerID {
if ([_delegate respondsToSelector:#selector(browserLostPeer:)]) {
[_delegate browserLostPeer:peerID];
}
}
- (MCSession *) getMCSession {
return _session;
}
But then I am getting as feedback in the console:
-[MCNearbyServiceBrowser invitePeer:toSession:withContext:timeout:] Bad argument session=nil
When I check for the found Advertisers, everything is OK. My advertiser ipad is being found. But how can I manage the invite?
So I don't get it right now... When I send an invitation by the browser, what session do I have to use? On the iPad I set up the session like you can see in the "automaticAdvertiseWithName" method. but on the iphone I don't do this when calling "automaticBrowsingWithName"... Is that the problem? And don't they have to be the same session to successfully connect them? And how can I successfully invite my advertiser ipad to the browser?
I am confused by the notion of creating a new session when one has already been created by the advertiser.
I am actually not sure, if the delegate didReceiveInvitation is adding the peer to the connectedPeers at all.
- (void)automaticAdvertiseWithName:(NSString *)name {
MCPeerID *peerID = [[MCPeerID alloc] initWithDisplayName:name];
self.session = [[MCSession alloc] initWithPeer:peerID];
self.session.delegate = self;
_advertiser = [[MCNearbyServiceAdvertiser alloc] initWithPeer:peerID discoveryInfo:nil serviceType:kServiceType];
_advertiser.delegate = self;
[_advertiser startAdvertisingPeer];
}
- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didReceiveInvitationFromPeer:(MCPeerID *)peerID withContext:(NSData *)context invitationHandler:(void (^)(BOOL, MCSession *))invitationHandler {
BOOL accept = YES;
invitationHandler(accept, self.session);
NSLog(#"Invitation accepted: %#", self.session);
}
And when I call the property "connectedPeers" on my session, there are no connected peers at all, even though the delegate found one. Did I make a mistake there?
Your problem is that your session is null at the time you call invitePeer:toSession:withContext:timeout...Anyway you have two options to fix this.
You have two options :
Option 1
- move the peerID creation, session creation and session delegate assignment in a place where its executed at all time. For example in the init code for MultipeerConnectivityService class of if its a UIViewController in the viewDidLoad.
Option 2
- add the following snippet before you call "invitePeer:toSession:withContext:timeout:"
if (!_session) {
MCPeerID *peerID = [[MCPeerID alloc] initWithDisplayName:#"Browser"]; // you can customize the name here
_session = [[MCSession alloc] initWithPeer:peerID];
_session.delegate = self;
}
Hope this helps ...good luck!

ShareKit: Customizing text for different sharers (SHKActionSheet)

According to the official FAQ from ver.2 to customize your text/content depending on what sharer was selected by the user, you need:
subclass from SHKActionSheet and override
dismissWithClickedButtonIndex
set your new subclass name in
configurator (return it in (Class)SHKActionSheetSubclass;).
It doesn't work for me. But even more: I put
NSLog(#"%#", NSStringFromSelector(_cmd));
in (Class)SHKActionSheetSubclass to see if it's even got called. And it's NOT ;(( So ShareKit doesn't care about this config option...
Has anybody worked with this before?
thank you!
UPD1: I put some code here.
Here's how my subclass ITPShareKitActionSheet looks like. According to the docs I need to override dismissWithClickedButtonIndex:animated:, but to track if my class gets called I also override the actionSheetForItem::
+ (ITPShareKitActionSheet *)actionSheetForItem:(SHKItem *)item
{
NSLog(#"%#", NSStringFromSelector(_cmd));
ITPShareKitActionSheet *as = (ITPShareKitActionSheet *)[super actionSheetForItem:item];
return as;
}
- (void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animate
{
NSLog(#"%#", NSStringFromSelector(_cmd));
NSString *sharersName = [self buttonTitleAtIndex:buttonIndex];
[self changeItemForService:sharersName];
[super dismissWithClickedButtonIndex:buttonIndex animated:animate];
}
And here's what I do in code to create an action sheet when user presses 'Share' button:
- (IBAction)shareButtonPressed:(id)sender
{
// Create the item to share
SHKItem *item = [SHKItem text:#"test share text"];
// Get the ShareKit action sheet
ITPShareKitActionSheet *actionSheet = [ITPShareKitActionSheet actionSheetForItem:item];
// Display the action sheet
[actionSheet showInView:self.view]; // showFromToolbar:self.navigationController.toolbar];
}
When I run this code, press 'Share' button and select any sharer I expect to get two lines in log:
actionSheetForItem: - custom action sheet got created
dismissWithClickedButtonIndex:animated: - custom mechanics to
process action sheet's pressed button got called.
But for some reason I get only the first line logged.
I was having the same issues but I've suddenly got it to call my Subclass successfully.
Firstly My Configurator is setup as so:
-(Class) SHKActionSheetSubclass{
return NSClassFromString(#"TBRSHKActionSheet");
}
Now My Subclass:
.h File
#import "SHKActionSheet.h"
#interface TBRSHKActionSheet : SHKActionSheet
#end
.m implementation override:
#import "TBRSHKActionSheet.h"
#import "SHKActionSheet.h"
#import "SHKShareMenu.h"
#import "SHK.h"
#import "SHKConfiguration.h"
#import "SHKSharer.h"
#import "SHKShareItemDelegate.h"
#implementation TBRSHKActionSheet
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
+ (SHKActionSheet *)actionSheetForItem:(SHKItem *)i
{
NSLog(#"%#", NSStringFromSelector(_cmd));
SHKActionSheet *as = [self actionSheetForType:i.shareType];
as.item = i;
return as;
}
- (void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated
{
NSInteger numberOfSharers = (NSInteger) [sharers count];
// Sharers
if (buttonIndex >= 0 && buttonIndex < numberOfSharers)
{
bool doShare = YES;
SHKSharer* sharer = [[NSClassFromString([sharers objectAtIndex:buttonIndex]) alloc] init];
[sharer loadItem:item];
if (shareDelegate != nil && [shareDelegate respondsToSelector:#selector(aboutToShareItem:withSharer:)])
{
doShare = [shareDelegate aboutToShareItem:item withSharer:sharer];
}
if(doShare)
[sharer share];
}
// More
else if ([SHKCONFIG(showActionSheetMoreButton) boolValue] && buttonIndex == numberOfSharers)
{
SHKShareMenu *shareMenu = [[SHKCONFIG(SHKShareMenuSubclass) alloc] initWithStyle:UITableViewStyleGrouped];
shareMenu.shareDelegate = shareDelegate;
shareMenu.item = item;
[[SHK currentHelper] showViewController:shareMenu];
}
[super dismissWithClickedButtonIndex:buttonIndex animated:animated];
}
Finally on my implementation file I've not modified the call to SHKActionSheet as Vilem has suggested because of some dependancies that seemed to cause conflicts for me.
So this is my caller (straight from tutorial):
NSURL *url = [NSURL URLWithString:#"http://getsharekit.com"];
SHKItem *item = [SHKItem URL:url title:#"ShareKit is Awesome!" contentType:SHKURLContentTypeWebpage];
// Get the ShareKit action sheet
SHKActionSheet *actionSheet = [SHKActionSheet actionSheetForItem:item];
// ShareKit detects top view controller (the one intended to present ShareKit UI) automatically,
// but sometimes it may not find one. To be safe, set it explicitly
[SHK setRootViewController:self];
// Display the action sheet
[actionSheet showFromToolbar:self.navigationController.toolbar];
This Calls no problems for me.
edit: by far the best way to achieve this is to use SHKShareItemDelegate. More info is in ShareKit's FAQ.

Why isn't multithreading working in this implementation?

Q1: Can I call a method and have it execute on a background thread from inside another method that is currently executing on the main thread?
Q2: As an extension of the above, can I call a method and have it execute on a background thread from inside another method that is currently executing on some other background thread itself?
Q3: And one final question given the above : if I initialize an instance of some object X on some thread (main/background) and then have a method Y, of that object X, executing on some other background thread, can this method Y send messages and update an int property (e.g. of that Object X, or is such communication not possible ?
The reason I'm asking this last question is because I've been going over and over it again and I can't figure what is wrong here:
The following code returns zero acceleration and zero degrees values :
MotionHandler.m
#implementation MotionHandler
#synthesize currentAccelerationOnYaxis; // this is a double
-(void)startCompassUpdates
{
locationManager=[[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate=self;
[locationManager startUpdatingHeading];
NSLog(#"compass updates initialized");
}
-(int) currentDegrees
{
return (int)locationManager.heading.magneticHeading;
}
-(void) startAccelerationUpdates
{
CMMotionManager *motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 0.01;
[motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue]
withHandler:^(CMDeviceMotion *motion, NSError *error)
{
self.currentAccelerationOnYaxis = motion.userAcceleration.y;
}
];
}
#end
Tester.m
#implementation Tester
-(void)test
{
MotionHandler *currentMotionHandler = [[MotionHandler alloc] init];
[currentMotionHandler performSelectorInBackground:#selector(startCompassUpdates) withObject:nil];
[currentMotionHandler performSelectorInBackground:#selector(startAccelerationUpdates) withObject:nil];
while(1==1)
{
NSLog(#"current acceleration is %f", currentMotionHandler.currentAccelerationOnYaxis);
NSLog(#"current degrees are %i", [currentMotionHandler currentDegrees]);
}
SomeViewController.m
#implementation SomeViewController
-(void) viewDidLoad
{
[myTester performSelectorInBackground:#selector(test) withObject:nil];
}
#end
However, the following code returns those values normally :
Tester.m
#interface Tester()
{
CLLocationManager *locationManager;
double accelerationOnYaxis;
// more code..
}
#end
#implementation Tester
- (id) init
{
locationManager=[[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.delegate=self;
[locationManager startUpdatingHeading];
// more code..
}
-(void) test
{
CMMotionManager *motionManager = [[CMMotionManager alloc] init];
motionManager.deviceMotionUpdateInterval = 0.01;
[motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]
withHandler:^(CMDeviceMotion *motion, NSError *error)
{
accelerationOnYaxis = motion.userAcceleration.y;
}
];
while(1==1)
{
NSLog(#"current acceleration is %f", accelerationOnYaxis);
NSLog(#"current degrees are %i", locationManager.heading.magneticHeading);
}
}
SomeViewController.m
#implementation SomeViewController
-(void) viewDidLoad
{
[myTester performSelectorInBackground:#selector(test) withObject:nil];
}
What's wrong with the first version? I really want to use that first one because it seems much better design-wise.. Thank you for any help!
Calling performSelectorInBackground:withObject: is the same as if you called the detachNewThreadSelector:toTarget:withObject: method of NSThread with the current object, selector, and parameter object as parameters (Threading Programming Guide). No matter where you call it, a new thread will be created to perform that selector. So to answer your first two questions: yes and yes.
For your final question, as long as this Object X is the same object in both methods, any of X's properties can be updated. But, beware that this can yield unexpected results (ie. see Concurrency Programming Guide). If multiple methods are updating X's property, values can be overwritten or disregarded. But, if you are only updating it from method Y and reading it from all other methods, such problems shouldn't occur.
You should take a look at the Grand Central Dispatch documentation from Apple. It allows you to use multiple threads in a block-based structure.
2 importants function are dispatch_sync() and dispatch_async().
Some examples:
To execute a certain block of code on a background thread and wait until it is finished:
__block id someVariable = nil;
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
// do some heavy work in the background
someVariable = [[NSObject alloc] init];
});
NSLog(#"Variable: %#", someVariable);
This function modifies the variable someVariable which you can use later on. Please note that the main thread will be paused to wait for the background thread. If that is not what you want, you can use dispatch_async() as follows:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
// do some heavy work in the background
NSObject *someVariable = [[NSObject alloc] init];
// notify main thread that the work is done
dispatch_async(dispatch_get_main_queue(), ^{
// call some function and pass someVariable to it, it will be called on the main thread
NSLog(#"Variable: %#", someVariable);
});
});