Application crash while accessing data element of linked list when data is NULL - ios

I am using following code to traverse through linked list in objective c
const MSList *calls = linphone_core_get_calls(LC);
if (calls == NULL)
{
[self dismissCtrl];
//how to check current is which screen is on
// while ((currentView == CallView.compositeViewDescription) ||
// (currentView == CallIncomingView.compositeViewDescription) ||
// (currentView == CallOutgoingView.compositeViewDescription)) {
// [self popCurrentView];
// }
} else {
linphone_call_resume((LinphoneCall *)calls->data);
while (calls)
{
if(calls->data != NULL && calls->data != nil && calls->data != (__bridge void *)((id)[NSNull null]))
{
//crash
if (linphone_call_get_state((LinphoneCall *)calls->data) == LinphoneCallIncomingReceived ||
linphone_call_get_state((LinphoneCall *)calls->data) == LinphoneCallIncomingEarlyMedia) {
[self displayIncomingCall:(LinphoneCall *)calls->data];
break;
}
}
calls = calls->next;
}
Application is crashing when entire list is not null but its data,previous or next value is NULL. I have added code to check if data is NULL but if it(data) is NULL, then i will not be able to access it and in condition itself application is crashing. How to prevent this ? I have attached screen-shot for where application is crashing and what is the value that list contains at that time.

if (calls == NULL) {
[self dismissCtrl];
//how to check current is which screen is on
// while ((currentView == CallView.compositeViewDescription) ||
// (currentView == CallIncomingView.compositeViewDescription) ||
// (currentView == CallOutgoingView.compositeViewDescription)) {
// [self popCurrentView];
// }
}
else
{
size_t count = bctbx_list_size(calls);
linphone_call_resume((LinphoneCall *)calls->data);
int i = 0;
while (calls )
{
if(i < count)
{
if ( calls->data == (__bridge void *)((id)[NSNull null]) || calls->data == NULL || calls->data == nil )
{
return;
}
LinphoneCall *objCall = (LinphoneCall *)calls->data;
LinphoneCallState state = (objCall != NULL) ? linphone_call_get_state(call) : 0;
if (state == LinphoneCallIncomingReceived ||
state == LinphoneCallIncomingEarlyMedia)
{
[self displayIncomingCall:(LinphoneCall *)calls->data];
break;
}
//calls ? calls->data : NULL
// calls = calls ? calls->next : NULL;
calls = calls->next;
i = i+1;
}
else
{
break;
}
}

Related

how to use the Microsoft Speech API: iOS Speech-to-Text Client Library in swift?

As I am new to swift language I know how to convert speech to text in objective c using the microsoft API but as part of client request I need that in swift language .can anyone help me how to do that in swift language. I also added the sample code which I used in objective c
-(void)onFinalResponseReceived:(RecognitionResult*)response {
bool isFinalDicationMessage = self.mode == SpeechRecognitionMode_LongDictation &&
(response.RecognitionStatus == RecognitionStatus_EndOfDictation ||
response.RecognitionStatus == RecognitionStatus_DictationEndSilenceTimeout);
if (nil != micClient && self.useMicrophone && ((self.mode == SpeechRecognitionMode_ShortPhrase) || isFinalDicationMessage)) {
// we got the final result, so it we can end the mic reco. No need to do this
// for dataReco, since we already called endAudio on it as soon as we were done
// sending all the data.
[micClient endMicAndRecognition];
}
if ((self.mode == SpeechRecognitionMode_ShortPhrase) || isFinalDicationMessage) {
dispatch_async(dispatch_get_main_queue(), ^{
[[self startButton] setEnabled:YES];
});
}
if (!isFinalDicationMessage) {
dispatch_async(dispatch_get_main_queue(), ^{
[self WriteLine:(#"********* Final n-BEST Results *********")];
for (int i = 0; i < [response.RecognizedPhrase count]; i++) {
RecognizedPhrase* phrase = response.RecognizedPhrase[i];
[self WriteLine:[[NSString alloc] initWithFormat:(#"[%d] Confidence=%# Text=\"%#\""),
i,
ConvertSpeechRecoConfidenceEnumToString(phrase.Confidence),
phrase.DisplayText]];
}
[self WriteLine:(#"")];
});
}
}
//convert speech
OSStatus status = [micClient startMicAndRecognition];
if (status) {
[self WriteLine:[[NSString alloc] initWithFormat:(#"Error starting audio. %#"),
ConvertSpeechErrorToString(status)]];
}
NSString* ConvertSpeechErrorToString(int errorCode) {
switch ((SpeechClientStatus)errorCode) {
case SpeechClientStatus_SecurityFailed: return #"SpeechClientStatus_SecurityFailed";
}
Try this:
func onFinalResponseReceived(_ response: RecognitionResult?) {
let isFinalDicationMessage: Bool = mode == SpeechRecognitionMode_LongDictation && (response?.recognitionStatus == RecognitionStatus_EndOfDictation || response?.recognitionStatus == RecognitionStatus_DictationEndSilenceTimeout)
if nil != micClient && useMicrophone && ((mode == SpeechRecognitionMode_ShortPhrase) || isFinalDicationMessage) {
// we got the final result, so it we can end the mic reco. No need to do this
// for dataReco, since we already called endAudio on it as soon as we were done
// sending all the data.
micClient.endMicAndRecognition()
}
if (mode == SpeechRecognitionMode_ShortPhrase) || isFinalDicationMessage {
DispatchQueue.main.async(execute: {() -> Void in
self.startButton().enabled = true
})
}
if !isFinalDicationMessage {
DispatchQueue.main.async(execute: {() -> Void in
self.writeLine(("********* Final n-BEST Results *********"))
var i = 0
while i < response.recognizedPhrase.count() {
var phrase: RecognizedPhrase? = response.recognizedPhrase[i]
if let aText = phrase?.displayText {
self.writeLine(("[\(i)] Confidence=\(ConvertSpeechRecoConfidenceEnumToString(phrase?.confidence)) Text=\"\(aText)\""))
}
i
}
i += 1
self.writeLine((""))
})
}
}
// edit:
var status: OSStatus = micClient.startMicAndRecognition()
func (int errorCode) -> String? {
switch errorCode as? SpeechClientStatus {
case SpeechClientStatus_SecurityFailed:
return "SpeechClientStatus_SecurityFailed"
}
}

IONIC/AngularJs on IOS - wrong innerWidth and innerHeight when changing screen orientation

It's my first time asking a question on stackoverflow, so i'll try to be as specific as I can. Thanks for your help.
Currently I'm developing an application for Androïd and IOS with Angular/IONIC solution.
Actually I've developed a service using cordova-plugin-screen-orientation 1.4.2 version plugin to change the orientation of my screen for some views. In fact, that work perfectly on both OS. But I also need when it's done, to catch the width and height of my device.
So there is my problem. On Android everything works, but on IOS, it looks like when I change the orientation I catch always the old values. (if I change for a landscape, I catch the previous portrait orientation values).
I tried different algorythm like the more simple : change the orientation and when it's done catch the values.
Currently I'm trying with a watcher, for the same result.
Here is my code :
class WindowService extends Service {
constructor($resource,$config, $window, Watcher) {
'ngInject';
super();
this.orientations = {
1:"portrait",
2:"landscape"
}
//imported library
this.md = new MobileDetect($window.navigator.userAgent);
// if it's a tablet Android, md.tablet() != null && md.os() == 'AndroidOS'
// if it's an iPad md.tablet() == 'iPad'
// if it's an iPhone md.mobile() == 'iPhone'
// if it's an Android phone, md.phone() != null && md.os() == 'AndroidOS'
console.log("md > ", this.md.mobile());
this.maxHeight = "100vh";
this.maxWidth = "100vw";
if (this.isAndroid()){
this.maxHeight = $window.innerHeight + "px";
this.maxWidth = $window.innerWidth + "px";
this.maxHeightWatcher = Watcher.watch(() => $window.innerHeight, innerHeight => {
this.maxHeight = $window.innerHeight + "px";
this.maxWidth = $window.innerWidth + "px";
});
}
}
setOrientation(){
this.invoke(($window) => {
if ($window.screen.unlockOrientation){
$window.screen.unlockOrientation();
if ((this.md.phone() != null && this.md.os() == 'AndroidOS') || this.md.mobile() == 'iPhone'){
$window.screen.lockOrientation('portrait');
}else if ((this.md.tablet() != null && this.md.os() == 'AndroidOS') || this.md.tablet() == 'iPad'){
$window.screen.lockOrientation('landscape');
}else {
$window.screen.lockOrientation('landscape');
}
}
});
}
//THIS S THE FUNCTION I CALL
changeOrientation(orientationId){
this.invoke(($window) => {
this.lockScreenOrientation($window, orientationId).then(res => {
console.log("changeOrientation > ", res);
}).catch(err => {
console.log("changeOrientation > ", err);
});
});
}
lockScreenOrientation($window, orientationId){
if (this.orientations[orientationId] != undefined){
if (this.orientations[orientationId] != $window.screen.orientation){
if ($window.screen.unlockOrientation){
$window.screen.unlockOrientation();
console.log("lockOrientation > ", $window.screen.lockOrientation(this.orientations[orientationId]));
return Promise.resolve(this.orientations[orientationId]);
}else{
return Promise.reject("[ERROR] cordova-plugin-screen-orientation hadn't been loaded.")
}
}else{
return Promise.resolve(this.orientations[orientationId]);
}
}else{
return Promise.reject("[ERROR] The orientation specified is Unknown.")
}
}
getDevice(){
if ((this.md.phone() != null && this.md.os() == 'AndroidOS')){
return "Android Smartphone";
}else if (this.md.mobile() == 'iPhone'){
return "iPhone";
}else if ((this.md.tablet() != null && this.md.os() == 'AndroidOS')){
return "Android Tablet";
}else if (this.md.tablet() == 'iPad'){
return "iPad";
}else
return "Unknown";
}
isSmartphone(){
if ((this.md.phone() != null && this.md.os() == 'AndroidOS') || this.md.mobile() == 'iPhone'){
return true;
}
return false;
}
isTablet(){
if ((this.md.tablet() != null && this.md.os() == 'AndroidOS') || this.md.tablet() == 'iPad')
return true;
return false;
}
isIOS() {
if (this.md.mobile() == 'iPhone' || this.md.tablet() == 'iPad')
return true;
return false;
}
isAndroid() {
if ((this.md.phone() != null && this.md.os() == 'AndroidOS')
|| (this.md.tablet() != null && this.md.os() == 'AndroidOS'))
return true;
return false;
}
getMaxHeight(){
return this.maxHeight;
}
getMaxWidth(){
return this.maxWidth;
}
}
Service.register(WindowService);
<ion-side-menu-content drag-content="false" ng-controller="HeaderController" style="height:{{view.maxHeight}};width: {{view.maxWidth}};">
....
</ion-side-menu-content>
The class Watcher is just an little extension of the basic watcher of angular. It works the same way.
[edit] Sorry I forgot to specify something : as you can see in the js code, in the constructor method, if it's IOS I just put 100vh fr the height and 100vw for the width. And I have the same result : the change from portrait to landscape keep the portrait size values.

Tic tac toe programming iOS

For some reason the function the checkForWin is returning always a NO.
Because of that I am not able to retrieve the winner.
Else if suggest a different logic to judge winner
I am using this function every time user puts up a symbol
-(BOOL) checkForWin{
NSLog(#"yes");
// HORIZONTAL WINS
if((s1.image == s2.image) & (s2.image == s3.image) & (s1.image != NULL))
{
return YES;
}
else if((s4.image == s5.image) & (s5.image == s6.image) & (s4.image != NULL))
{
return YES;
}
else if((s7.image == s8.image) & (s8.image == s9.image) & (s7.image != NULL))
{
return YES;
}
// VERTICAL WINS
else if((s1.image == s4.image) & (s4.image == s7.image) & (s1.image != NULL))
{
return YES;
}
else if((s2.image == s5.image) & (s5.image == s8.image) & (s2.image != NULL))
{
return YES;
}
else if((s3.image == s6.image) & (s6.image == s9.image) & (s3.image != NULL))
{
return YES;
}
// DIAGONAL WINS
else if((s1.image == s5.image) & (s5.image == s9.image) & (s1.image != NULL))
{
return YES;
}
else if((s3.image == s5.image) & (s5.image == s7.image) & (s3.image != NULL))
{
return YES;
}
//right now return 1 becuase we havn't implemented this yet
else{
return NO;
}
}
-(void)displayWinner{
if([self checkForWin] == YES){
if(playerToken==1){
lbl2.text =#"X is the WINNER";
} else {
lbl2.text =#"O is the WINNER";
}
}
}
Maybe you can write
if([s1.image isEqual:s2.image2]){
}
this code instead of this control statement
if((s1.image == s2.image) & (s2.image == s3.image) & (s1.image != NULL))
{
return YES;
}
The answer by Yılmaz Gürsoy is probably correct.
The reason, is that you are comparing the references to the images, and not the image data. The references are probably not the same, while the data probably is.
He is suggesting that you compare the data instead of the references.
In my oppinion though, you should actually add a member to the s# object, containing a tristate value. could be an integer.
/**
s.x is avalue indicating which image is shown (x, O, or empty)
x > 0 means 'X'
x == 0 means 'O'
x < 0 means empty
**/
and then set it when you assign the image. and check against that.
otherwise you will be wasting time comparing data, to get the exact same end result.

Xamarin iOS Bluetooth Low Energy - CBPeripheral.UpdatedCharacteristicValue reading TX characteristic shows unexpected data

I recently received a BLE device for Bluetooth to Serial. It uses TruConnect and I'm trying to get it to communicate with my serial device. The serial device receives communication over a serial cable and echoes back anything that is sent to it as well as any results from a command that is sent.
Right now I'm simply trying to send TruConnect commands to the BLE device to check the current baud rate that the BLE device is set for.
I wrote some code based on this TruConnect guide that I found:
https://truconnect.ack.me/1.5/apps/communicating_via_ble#reading_from_a_truconnect_device_serial_interface.
The problem seems to be that whenever I try to read anything from the tx characteristic when there should be data, the data is not right.
Setting up CBPeripheral events:
private void setupPerif(CBPeripheral perf)
{
selectedPeripheral = perf;
selectedPeripheral.UpdatedCharacterteristicValue += (sender, e) =>
{
var c = e.Characteristic;
if (c != null)
{
var uuid = c.UUID.ToString(true).ToLower();
if (uuid == UUID_RX)
{
//
}
else if (uuid == UUID_TX)
{
// expecting bytes to contain valid response data
// it almost always contains twenty 0s.
byte[] bytes = c.Value.Where(i => i != 13).ToArray();
var invalidBytes = c.Value.Where(i => i > 127).ToArray();
var nonZeros = c.Value.Where(i => i != 0).ToArray();
if (nonZeros.Length < 1)
{
return;
}
else
{
foreach (byte b in bytes)
handler.handleByteReceived((char)b);
}
}
else if (uuid == UUID_MODE)
{
//
}
}
};
selectedPeripheral.DiscoveredService += (sender, e) =>
{
var services = selectedPeripheral.Services;
if (services != null)
{
foreach (CBService service in services)
{
if (service.UUID.ToString(true).ToLower() == UUID_TRUCONNECT)
{
truConnect = service;
selectedPeripheral.DiscoverCharacteristics(truConnect);
}
}
}
};
selectedPeripheral.DiscoveredCharacteristic += (sender, e) =>
{
if (truConnect != null && truConnect.Characteristics != null)
{
foreach (CBCharacteristic c in truConnect.Characteristics)
{
var uuidString = c.UUID.ToString(true).ToLower();
if (uuidString == UUID_RX)
{
rx = c;
}
else if (uuidString == UUID_TX)
{
tx = c;
}
else if (uuidString == UUID_MODE)
{
mode = c;
// set to stream mode
selectedPeripheral.WriteValue(NSData.FromArray(new byte[] { MODE_COMMAND }), mode, CBCharacteristicWriteType.WithResponse);
}
}
}
};
selectedPeripheral.WroteCharacteristicValue += (sender, e) =>
{
// if UUID is for RX, we just wrote to RX. Drill down to
// TX characteristic and read it. This will trigger
// the UpdatedCharacteristicValue event.
string uuid = e.Characteristic.UUID.ToString(true).ToLower();
if (uuid == UUID_RX)
{
var services = selectedPeripheral.Services;
if (services != null)
{
foreach (CBService s in services)
{
if (s.UUID.ToString(true).ToLower() == UUID_TRUCONNECT)
{
var charachteristics = s.Characteristics;
if (charachteristics != null && charachteristics.Length > 0)
{
foreach (CBCharacteristic c in charachteristics)
{
if (c.UUID.ToString(true).ToLower() == UUID_TX)
{
Timer t = new Timer(new TimerCallback(delegate(object o)
{
selectedPeripheral.ReadValue(c);
}), null, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(-1));
}
}
}
}
}
}
}
};
manager.ConnectPeripheral(selectedPeripheral);
}
Writes to rx. This is what should be used to actually send commands.
public void sendCommand(string command)
{
command += endString + "\n";
if (rx != null)
{
NSData d = NSData.FromString(command);
foreach (CBService s in selectedPeripheral.Services)
{
if (s.UUID.ToString(true).ToLower() == UUID_TRUCONNECT)
foreach (CBCharacteristic c in s.Characteristics)
{
if (c.UUID.ToString(true).ToLower() == UUID_RX)
selectedPeripheral.WriteValue(NSData.FromString(command), c, CBCharacteristicWriteType.WithResponse);
}
}
}
}
So my question is, why am I not getting the expected data when the CBPeripheral.UpdatedCharacteristicValue event is called? Occasionally I will get the expected data, but it is quite rare, and I can't seem to find any logical reason or pattern that would explain why this is happening.
AHA! I figured it out!
The problem was that I need to set the notify value for the appropriate characteristics. After doing that, I didn't need to call CBPeripheral.ReadValue(CBCharacteristic).
selectedPeripheral.DiscoveredCharacteristic += (sender, e) =>
{
if (truConnect != null && truConnect.Characteristics != null)
{
foreach (CBCharacteristic c in truConnect.Characteristics)
{
var uuidString = c.UUID.ToString(true).ToLower();
if (uuidString == UUID_RX)
{
rx = c;
}
else if (uuidString == UUID_TX)
{
tx = c;
// set the notify value to true and poof!
// now CBPeripheral.UpdatedCharacteristicValue
// event will be triggered at the appropriate time.
selectedPeripheral.SetNotifyValue(true, tx);
}
else if (uuidString == UUID_MODE)
{
mode = c;
// set to remote command mode
selectedPeripheral.WriteValue(NSData.FromArray(new byte[] { MODE_COMMAND }), mode, CBCharacteristicWriteType.WithResponse);
}
}
}
};

how to check if bond array is Null or empty in iphone sdk?

I want to check if my array is empty or null and not null or not empty. Below is some sample code I have written. Can you tell me if this is on the right track?
/// first time get data there
{
Bonds = Null;
User = {
DOB = "12/09/1988";
about = "test about";
city = CA;
};
success = True;
}
////////Second time get data there
{
Bonds = (
{
DOB = "12/09/1988";
about = "";
city = CA;
},
{
DOB = "12/09/1988";
about = "";
city = CA;
}
);
User = {
DOB = "12/09/1988";
about = about;
city = CA;
};
success = True;}
#try
{
if([Your_array objectAtIndex:int]== (id)[NSNull null] || [Your_array objectAtIndex:int]==0)
{
// if index get null
}
else
{
//your code if array index is not null
}
}
#catch (NSException * e)
{
NSLog(#"NSException");
}
If you are asking how to check for an empty array in Objective C (you mentioned iPhone SDK but not the language- Swift or Objective C) you can simply check the count.
if ([myArray count]==0) // the array is empty
{
...
}
try this
if(![Bonds isKindOfClass:[NSArray Class]]) // for non nil array and
if([Bounds firstObject]) //to check if array having at least one element
if array is not nil, and if not - check if it is not empty.
if (!array || !array.count){
......
}
try this
if(array && ![array isEqual:[NSNull null]] && [array count] > 0)
{
}
You can check like this
if ((NSNull*) Bonds !=[NSNull null] && Bonds!=nil && [array count] > 0)
{
}
if (!array || !array.count){
......
}

Resources