Is it possible to read app specific warning messages? - ios

I want to read the console of my application. My aim is find all messages like this:
Warning: Attempt to present <ChildViewController: 0x7b44e380> on <TopViewController: 0x7a65e5b0> which is already presenting (null)
I founded that on iOS7 you can’t read system messages.
Using Objective C to read log messages posted to the device console
In iOS 7 you can use ASL to read messages output by your own app, including on previous runs of the same build of your app, but not messages output by the system or by any other apps.
For my mind any warnings is a system messages. May be something changes on ios8?

It's possible to read from the "syslog.sock". There is source on Github which works under iOS8: https://github.com/eswick/ondeviceconsole
ASL no longer works from iOS7 onwards for system wide logs, iOS 7+ apps can only see their own log messages due to increased sandboxing.
If you only want to see your own app's logs, you can still use ASL:
aslmsg q, m;
int i;
const char *key, *val;
q = asl_new(ASL_TYPE_QUERY);
aslresponse r = asl_search(NULL, q);
while (NULL != (m = aslresponse_next(r)))
{
NSMutableDictionary *tmpDict = [NSMutableDictionary dictionary];
for (i = 0; (NULL != (key = asl_key(m, i))); i++)
{
NSString *keyString = [NSString stringWithUTF8String:(char *)key];
val = asl_get(m, key);
NSString *string = val?[NSString stringWithUTF8String:val]:#"";
[tmpDict setObject:string forKey:keyString];
}
NSLog(#"%#", tmpDict);
}
aslresponse_free(r);

Related

Sqlite shows EXC_BAD_ACCESS while executing query in ios

The code I am using for executing the query is as below:
NSString *score_query = #"Insert into tbl_assessment (Question,Answer,Option1,Option2,Option3,Explanation,Used,ImageName,Reference) values ('All of the following questions would be asked in a lifestyle questionnaire except:','Do you feel any pain in your chest when you perform physical activity?','Does your occupation cause you anxiety (mental stress)?','Does your occupation require extended periods of sitting?','Do you partake in any recreational activities (golf, tennis, skiing, etc.)?','NULL','N','NULL','NULL')";
NSLog(#"%#",score_query);
[database executeQuery:score_query];
I have generated this query dynamically. But I have added the query directly to the string.
But when I tried to execute this insert query, app crashes on below function:
- (NSArray )executeQuery:(NSString )sql, ... {
va_list args;
va_start(args, sql);
NSMutableArray *argsArray = [[NSMutableArray alloc] init];
NSUInteger i;
for (i = 0; i < [sql length]; ++i)
{
if ([sql characterAtIndex:i] == '?')
[argsArray addObject:va_arg(args, id)];
}
va_end(args);
NSArray *result = [self executeQuery:sql arguments:argsArray];
[argsArray release];
return result;
}
The dropbox for the classes I am using for database operation is given below:
https://www.dropbox.com/s/c4haxqnbh0re41c/Archive%202.zip?dl=0
I have already referred the below link but can't understand.
Sqlite shows EXC_BAD_ACCESS in ios SDK
In your example, you are only passing one argument to execQuery:, but your implementation is trying to pull additional arguments from the varargs every time it sees a '?' in the string, of which there are numerous '?'s.
That's causing the crash.

iOS Convert phone number to international format

In my iOS app I have to convert a phone number (taken in the contacts) and convert it in international format (to send SMS automatically with an extern library). I saw libPhoneNumber but the problem is that we have to enter the country code, and the app have to work in all (almost) countries, so I don't know what is the user's country.
Here is how the library works :
let phoneUtil = NBPhoneNumberUtil()
let phoneNumberConverted = try phoneUtil.parse("0665268242", defaultRegion: "FR") // So I don't know the country of the user here
print(try? phoneUtil.format(phoneNumberConverted, numberFormat: NBEPhoneNumberFormat.INTERNATIONAL))
formattedPhoneNumberSubstring takes a partial phone number string and formats it as the beginning of a properly formatted international number, e.g. "16463" turns to "+1 646-3".
NSString *formattedPhoneNumberSubstring(NSString *phoneNumber) {
NBPhoneNumberUtil *phoneUtil = [NBPhoneNumberUtil sharedInstance];
phoneNumber = [phoneUtil normalizeDigitsOnly:phoneNumber];
NSString *nationalNumber;
NSNumber *countryCode = [phoneUtil extractCountryCode:phoneNumber nationalNumber:&nationalNumber];
if ([countryCode isEqualToNumber:#0])
return phoneNumber;
NSString *regionCode = [[phoneUtil regionCodeFromCountryCode:countryCode] objectAtIndex:0];
NSString *paddedNationalNumber = [nationalNumber stringByPaddingToLength:15 withString:#"0" startingAtIndex:0];
NSString *formatted;
NSString *formattedSubstr;
for (int i=0; i < paddedNationalNumber.length; i++) {
NSError *error = nil;
formattedSubstr = [phoneUtil format:[phoneUtil parse:[paddedNationalNumber substringToIndex:i] defaultRegion:regionCode error:&error]
numberFormat:NBEPhoneNumberFormatINTERNATIONAL error:&error];
if (getExtraCharacters(formattedSubstr) > getExtraCharacters(formatted)) // extra characters means more formatted
formatted = formattedSubstr;
}
// Preparing the buffer for phoneNumber
unichar phoneNumberBuffer[phoneNumber.length+1];
[phoneNumber getCharacters:phoneNumberBuffer range:NSMakeRange(0, phoneNumber.length)];
// Preparing the buffer for formatted
unichar formattedBuffer[formatted.length+1];
[formatted getCharacters:formattedBuffer range:NSMakeRange(0, formatted.length)];
int j=0;
for(int i = 0; i < phoneNumber.length && j < formatted.length; i++) {
while(formattedBuffer[j] != phoneNumberBuffer[i]) j++;
j++;
}
return [formatted substringToIndex:j];
}
You can get the region using either the users locale or the users geo position.
See stackoverflow question get device location country code for more details.
If you don’t know the country code of a phone number, you can’t generate the international format of it.
You could try using the location of the phone or its region settings to guess the country code, but it won’t be reliable. For example, my phone number is Spanish, I’m currently in Italy and my region is set to New Zealand. My contact list contains numbers from all over the world, and if they weren’t entered in international format there would be no way to guess what country code to use for each number.
If you absolutely have to guess, the best approach might be to think about how the phone would interpret the numbers in the contact list itself. This would require you to determine the country code of the phone’s SIM card. See this answer to a related question for a way of doing that, or here’s some Swift code I’ve used:
let networkInfo = CTTelephonyNetworkInfo()
if let carrier = networkInfo.subscriberCellularProvider {
NSLog("Carrier: \(carrier.carrierName)")
NSLog("ISO: \(carrier.isoCountryCode)")
NSLog("MCC: \(carrier.mobileCountryCode)")
NSLog("MNC: \(carrier.mobileNetworkCode)")
}
The ISO country code can be used to look up a country code for dialling; an example table is in the answer linked above.

Trouble Comparing Bluetooth-Sent ASCII char in iOS

I have an iOS application that talks to a RedBearLab Arduino device. My code that I use to send an int via bluetooth from Arduino to iOS is as follows:
void sendMyInt(int myInt) {
char b[4];
String str;
str=String(myInt);
str.toCharArray(b,4);
for (int i; i < 3; i++) {
char toPrint = b[i];
ble_write(toPrint);
}
}
Here is my code on the receiving end:
-(void) bleDidReceiveData:(unsigned char *)data length:(int)length
{
NSData *d = [NSData dataWithBytes:data length:length];
NSLog([NSString stringWithFormat:#"%#",d]);
NSString *s = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding];
const char* clearChar = "!";
if ([self.label.text isEqualToString:#"Label"]) {
self.label.text = #"";
}
else if ([s isEqualToString:[NSString stringWithUTF8String:clearChar]]) {
self.label.text = #"";
}
else {
NSString *store = self.label.text;
NSString *full = [NSString stringWithFormat:#"%#%#",store,s];
self.label.text = full;
}
}
The final else statement fires somewhat as expected, and a value of 233! is printed out to the label over and over again, getting longer each time eventually forming things like 233!233!233! etc. As you can see, I am using a character (!) sent over a function to clear the label, but it never clears. The integer is the ASCII code for the exclamation point:
void clearLabel() {
int clearString = 33;
char excalamtion = clearString;
ble_write(excalamtion);
}
Why would this not clear the label? I assume it has something to do with the clashing formats, but I'm not really too good at that even after reading some documentation. For the else if statement I also tried this
if ([s isEqualToString:#"!"])
but that didn't work out either... Any help would be appreciated.
EDIT:
I forgot to put in my loop code so you can see function calls. Here it is:
void loop()
{
if ( ble_connected() ) {
int a = 223;
sendMyInt(a);
delay(1000);
clearLabel();
delay(1000);
}
ble_do_events();
}
EDIT 2:
Based on a suggestion by #Duncan C , I have isolated the problem to the fact that the data is being sent as one packet to the iPhone. Upon printing out my generated string when the data is received, the string 233! is received all at once rather than individual chars of 2 3 3, and one second later the signal to clear, !. The data takes two seconds to appear on my phone, indicating that both delays are being used. I need a way to separate the 2 3 3 packet from the ! packet.
First off, this line:
NSLog([NSString stringWithFormat:#"%#",d]);
Is sort of pointless. The stringWithFormat serves no real purpose, since NSLog takes a format string anyway.
Use this instead:
NSLog(#"%#", d);
You should probably also log the contents of "s" once you convert your NSData to an NSString. That will help you figure out what's going on.
What is likely going on is that your string is coming in as "233!", all together, 4 bytes at a time (assuming that your integer is == 233).
Your string is unlikely to ever contain just "!". Instead, it will likely contain "233!" (4 characters.) I say likely because it depends on how the data is packetized into BLE. Something that short should be sent all in 1 BLE packet, so you should get the entire string together.
You could use the NSString method rangeOfString: to search for your "!" string, and if it contains an "!", clear your label, but that won't really do any good either. If you're sending "233!", then the iOS code will see the exclamation point in the string it receives and simply clear the label.
Or does your arduino project first send "233", then after some other event, send the "!". You didn't make that clear.
Another problem: What does the Arduino String class do if the integer is less than 1000, or less than 100, and doesn't require 3 or 4 characters to convert to a char array? What is stored in the unused bytes? You're always sending 4 characters, which is probably wrong.
Adding in another ble_do_events(); after calling the sendMyInt(); function causes the data to be transmit in two separate packets.

Optimize apple system logs

+ (NSArray *)systemLogDictionariesForAppName:(NSString *)appName {
aslmsg q = asl_new(ASL_TYPE_QUERY);
asl_set_query(q, ASL_KEY_SENDER, [appName cStringUsingEncoding:NSASCIIStringEncoding], ASL_QUERY_OP_EQUAL);
aslresponse r = asl_search(NULL, q);
aslmsg m;
uint32_t i;
const char *key, *val;
NSMutableArray *systemLogDictionaries = [NSMutableArray array];
while (NULL != (m = aslresponse_next(r)))
{
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
for (i = 0; (NULL != (key = asl_key(m, i))); i++)
{
val = asl_get(m, key);
NSString *stringKey = [NSString stringWithCString:key encoding:NSUTF8StringEncoding];
NSString *stringVal = [NSString stringWithCString:val encoding:NSUTF8StringEncoding];
[dictionary setObject:stringVal forKey:stringKey];
}
[systemLogDictionaries addObject:dictionary];
}
aslresponse_free(r);
return systemLogDictionaries;
}
Above code will get apple system log. Problem is, it take around 8second to pull all the logs from Apple System Log (ASL). Is there any way to optimize asl_set_query to get data faster or any other way which I am missing.
Note: Can we create a ASL query which will take time stamp and we can get less number of data to process. This will solve the problem I think.
ASL supports a few different logging levels, so you could specify a more restrictive level.
For example you can add another query (according to the man page they are joined via the logical AND):
// ...
asl_set_query(q, ASL_KEY_SENDER, [appName cStringUsingEncoding:NSASCIIStringEncoding], ASL_QUERY_OP_EQUAL);
// 3 is error messages
asl_set_query(q, ASL_KEY_LEVEL, "3", ASL_QUERY_OP_LESS_EQUAL | ASL_QUERY_OP_NUMERIC);
//-- Check for time --//
/* A dumped entry with your code looks like:
ASLMessageID = 1825403;
"CFLog Local Time" = "2013-07-20 08:33:12.943";
"CFLog Thread" = 951f;
Facility = "com.apple.Safari";
GID = 20;
Host = "XXX.local";
Level = 4;
Message = "CFPropertyListCreateFromXMLData(): Old-style plist parser: missing semicolon in dictionary on line 3. Parsing will be abandoned. Break on _CFPropertyListMissingSemicolon to debug.";
PID = 183;
ReadUID = 501;
Sender = Safari;
Time = 1374305592;
TimeNanoSec = 943173000;
UID = 501;
Time is a Unix timestamp, so you can use it in your query with ASL_KEY_TIME and one of these operators: ASL_QUERY_OP_EQUAL, ASL_QUERY_OP_GREATER, ASL_QUERY_OP_GREATER_EQUAL, ASL_QUERY_OP_LESS, ASL_QUERY_OP_LESS_EQUAL, ASL_QUERY_OP_NOT_EQUAL
The code below, generates a unix timestamp for yesterday and dumps all messages that occurred yesterday or later.
(Nevermind the dirty/hacky way I generate the timestamp, that was just for testing purposes)
*/
NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow: -(60.0f*60.0f*24.0f)];
NSString *theDate = [NSString stringWithFormat:#"%d", (int)[yesterday timeIntervalSince1970]];
asl_set_query(q, ASL_KEY_TIME, [theDate cStringUsingEncoding:NSASCIIStringEncoding], ASL_QUERY_OP_GREATER_EQUAL | ASL_QUERY_OP_NUMERIC);
aslresponse r = asl_search(NULL, q);
//...
For some more information on the different error levels check: http://www.cocoanetics.com/2011/03/accessing-the-ios-system-log/
Note that, depending on the level you set and the level your log messages are, further filtering may have no effect (ie. if all messages that are actually logged for your app are of the same level)
Further note, unlike the debug level querying, I haven't yet used the timestamp querying in any productive code, but in a test it seems to work perfectly fine and is doing what it is supposed to do.

EXC_BAD_ACCESS error when using NSString getCString

I'm trying to parse some HTML. I use stringWithContentsOfURL to get the HTML. I attempt to load this into a character array so I can parse it, but I crash with the EXC_BAD_ACCESS error when getCString is called. Here is the relavent code:
- (void)parseStoryWithURL:(NSURL *)storyURL
{
_paragraphs = [[NSMutableArray alloc] initWithCapacity:10];
_read = NO;
NSError* error = nil;
NSString* originalFeed = [NSString stringWithContentsOfURL:storyURL encoding:NSUTF8StringEncoding error:&error];
_i = originalFeed.length;
char* entireFeed = malloc(_i*sizeof(char));
char* current = entireFeed;
char* lagger;
char* recentChars = malloc(7);
BOOL collectRecent = NO;
BOOL paragraphStarted = NO;
BOOL paragraphEnded = NO;
int recentIndex = 0;
int paragraphSize = 0;
NSLog(#"original Feed: %#", originalFeed);
_read = [originalFeed getCString:*entireFeed maxLength:_i encoding:NSUTF8StringEncoding];
I've also tried this passing the 'current' pointer to getCString but it behaves the same. From what I've read this error is typically thrown when you try to read from deallocated memory. I'm programming for iOS 5 with memory management. The line before that I print the HTML to the log and everything is fine. Help would be appreciated. I need to get past this error so I can test/debug my HTML parsing algorithms.
PS: If someone with enough reputation is allowed to, please add "getCString" as a tag. Apparently no one uses this function :(
There are several issues with your code - you're passing the wrong pointers and not reserving enough space. Probably the easiest is to use UTF8String instead:
char *entireFeed = strdup([originalFeed UTF8String]);
At the end you'll have to free the string with free(entireFeed) though. If you don't modify it you can use
const char *entireFeed = [originalFeed UTF8String];
directly.
If you want to use getCString, you'll need to determine the length first - which has to include the termination character as well as extra space for encoded characters, so something like:
NSUInteger len = [originalFeed lengthOfBytesUsingEncoding: NSUTF8StringEncoding] + 1;
char entireFeed[len];
[originalFeed getCString:entireFeed maxLength:len encoding:NSUTF8StringEncoding];
Try explicitly malloc'ing entireFeed with a length of _i (not 100% certain of this, as NSUTF8String might also include double byte unichars or wchars) instead of the wacky char * entireFeed[_i] thing you're doing.
I can't imagine char * entireFeed[_i] is working at run-time (and instead, you're passing a NULL pointer to your getCString method).
A few strange things;
char* entireFeed[_i]; allocates an array of char*, not an array of char. I suspect you want char entireFeed[_i] or char *entireFeed = malloc(_i*sizeof(char));
getCString takes a char* as a first parameter, that is, you should send it entireFeed instead of *entireFeed.
Also, note that the (UTF-8) encoding may add bytes to the result, so allocating the buffer the exact size of the input may cause the method to return NO (buffer too small). You should really use [originalFeed UTF8String] instead.

Resources