I would like to read console Log From iOS 10 - ios10

I was using this code but it is no longer working on iOS 10 because of changing all APIs related to Logging System.
+ (NSString *)getConsoleLog {
NSString *consoleLog = #"";
char fdate[24];
NSString *myPID = [NSString stringWithFormat:#"%d", getpid()];
aslmsg query, msg;
query = asl_new(ASL_TYPE_QUERY);
asl_set_query(query, ASL_KEY_PID, myPID.UTF8String, ASL_QUERY_OP_EQUAL);
aslresponse r = asl_search(NULL, query);
while ((msg = aslresponse_next(r))) {
NSString *secondsString = [NSString stringWithFormat:#"%s", asl_get(msg, ASL_KEY_TIME)];
NSString *nanoSecondsString = [NSString stringWithFormat:#"%s", asl_get(msg, ASL_KEY_TIME_NSEC)];
NSTimeInterval seconds = [secondsString doubleValue];
NSTimeInterval nanoSeconds = [nanoSecondsString doubleValue];
NSTimeInterval msgTime = seconds + nanoSeconds / NSEC_PER_SEC;
time_t timestamp = (time_t)msgTime;
struct tm *lt = localtime(&timestamp);
strftime(fdate, 24, "%Y-%m-%d %T", lt);
consoleLog = [consoleLog stringByAppendingFormat:#"%s.%03d %#\n", fdate, (int)(1000.0 * (msgTime - floor(msgTime))), [NSString stringWithFormat:#"%s", asl_get(msg, ASL_KEY_MSG)]];
}
aslresponse_free(r);
asl_free(query);
return consoleLog; }
Can anyone help?

Beginning in iOS 10 NSLog redirects to the new logging system and there is no search API.
From the WWDC 2016 Session 721 - Unified Logging and Activity Tracing
"...all of the legacy APIs, NSLog, asl log, message syslog, all of those will get redirected into the new system. ...but out-of-the-box if you just build with the new system it'll all get directed into the new logging architecture."
Time 41:47 "First off, all of the ASL logging APIs are now superseded by these new APIs and, therefore, those old APIs are deprecated. There is an interesting edge case though. A new API for searching the log data is not going to be made public in this release. What that means is that there's no equivalent to asl search functionality. If you absolutely depend on asl search in your system that may be a reason to wait for adopting the new logging system. There's also some APIs from activities that are being deprecated."

Related

Finding minor performance hogs in Objective-C

To discover perfomance hogs in a specific method I often do something like this:
// Some line of code
LogTimeInterval();
// Some other line of code
LogTimeInterval();
// Some other line of code
LogTimeInterval();
Where LogTimeInterval is defined as:
void LogTimeInterval()
{
static NSDate *_previousDate;
static NSInteger _counter = 0;
NSDate *date = [NSDate date];
if (!_previousDate) {
_previousDate = date;
}
NSLog(#"LINE %d: %f", _counter++, [_previousDate timeIntervalSinceDate:date]);
_previousDate = date;
}
This allows me to discover which lines of code are taking more time than necessary. However, it requires modifying the code and can be cumbersome when there is branching logic.
Is there a most efficient way to do this micro-level analysis for a specific method?
Try XCode's built-in Profiler. Among the tools it has, there is a time profiler. Check this link for a nice tutorial on how to use it

Crash log without crash?

Hey this may be a stupid question but I couldn't find the answer anywhere, apologies if the answer is easily found and if my research skills are pants.
anyway is it possible to generate a crash report when an app doesn't crash? so say if a user encounters a bug could there be an option to allow them to generate a crash report which can then be sent to me? also how would I go about doing this?
Thanks for any help :)
I have used it couple of times when I had to print stack trace:
+ (NSArray *)backtrace
{
void* callstack[128];
int frames = backtrace(callstack, 128);
char **strs = backtrace_symbols(callstack, frames);
int i;
NSMutableArray *backtrace = [NSMutableArray arrayWithCapacity:frames];
for (
i = UncaughtExceptionHandlerSkipAddressCount;
i < UncaughtExceptionHandlerSkipAddressCount +
UncaughtExceptionHandlerReportAddressCount;
i++)
{
[backtrace addObject:[NSString stringWithUTF8String:strs[i]]];
}
free(strs);
return backtrace;
}
"When an application crashes on the iPhone, it disappears without telling the user what happened. However, it is possible to add exception and signal handling to your applications so that an error message can be displayed to the user or you can save changes. It is even possible to try to recover from this situation without crashing at all."
Look at http://cocoawithlove.com/2010/05/handling-unhandled-exceptions-and.html
Here's what I use for my stacktraces:
NSArray *callStackArray = [exception callStackReturnAddresses];
int frameCount = [callStackArray count];
void *backtraceFrames[frameCount];
for (int i=0; i < frameCount; i++) {
backtraceFrames[i] = (void *)[[callStackArray objectAtIndex:i] unsignedIntegerValue];
}
char **strs = backtrace_symbols(backtraceFrames, frameCount);
NSMutableArray *backtraceArray = [NSMutableArray arrayWithCapacity:frameCount];
for (int i = 0; i < frameCount; i++) {
NSString *entry = [NSString stringWithUTF8String:strs[i]];
[backtraceArray addObject:entry];
}
free(strs);
You just have to make sure you don't do any harm to your app: http://landonf.bikemonkey.org/2011/09/14. You could also use PLCrashReporter to handle all your crashes or if you're lazy like me, use a service like Crittercism
I used to use backtrace_symbols for handling my crashes too, but then I found out that it could be dangerous since the method is not async-safe. I've since looked at a bunch of crash reporting solutions and went with Crittercism for my apps and it's been pretty sweet!
I suggest you check out TestFlight SDK released a few days ago. It has some awesome features like remote logging and even live crash reports.
For an ad hoc version, you could just call the function abort(), or throw and exception of some kind.
An App Store version will not be allowed to ship if it crashes at all during testing.

Write stderr on iPhone to both file and console

I'm following the suggestion in the answer here for redirecting NSLog output on an iOS device to a file, which works great. The problem is that it no longer shows up in the console on the device. What I'd really like is a way to tee the stderr stream to both the console and the file. Does anyone have an idea how to do that?
I found an acceptable answer on another thread (NSLog() to both console and file).
The solution provided there is to only redirect to a file if a debugger is not detected, like this:
if (!isatty(STDERR_FILENO))
{
// Redirection code
}
Thanks to Sailesh for that answer.
Once you freopen() the file descriptor, you can read from it and do as you please with the data. Some ideas from this will be useful to you.
You could either write it back out to stdout, or try to write directly to /dev/console. I've never tried to open /dev/console on an iPhone, but I'm guessing it's possible despite being outside of the sandbox. I'm not sure how the app review process will treat it.
Or you can redirect to a TCP socket and view on a remote telnet client. No need for XCode this way!
Basically:
Create a standard C function which calls an Obj-C static method:
void tcpLogg_log(NSString* fmt, ...)
{
va_list args;
va_start(args, fmt);
[TCPLogger tcpLog:fmt :args];
va_end(args);
}
The static Obj-C method:
(void)tcpLog:(NSString*)fmt :(va_list)args
{
NSLogv(fmt, args);
if(sharedSingleton != nil && sharedSingleton.socket != nil)
{
NSString *time = [sharedSingleton.dateFormat stringFromDate:[NSDate date]];
NSString *msg = [[NSString alloc] initWithFormat:fmt arguments:args];
mach_port_t tid = pthread_mach_thread_np(pthread_self());
NSString *str = [NSString stringWithFormat:#"%#[%X]: %#\r\n", time, tid, msg];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[sharedSingleton.socket writeData:data
withTimeout:NETWORK_CLIENT_TIMEOUT_PERIOD
tag:0];
}
}
Then in your .pch file, add the following lines to override NSLog()
define NSLog(...) tcpLogg_log(__VA_ARGS__);
void tcpLogg_log(NSString* fmt, ...);
Of course more details are required to handle the TCP Socket. Working source code is available here:
https://github.com/driedler/iOS-TCP-Logger/wiki/About

Parsing my flat-file on iPhone is a pain in the ***, please Help me out

I am programming an iPhone App which is supposed to parse a flat-file from the web, create managed objects from the flat-file and later on should display them in an UITableView.
There are no problems with the saving and the displaying, but I just can't get the hang of a good Parser.
Thats the file I want to parse: Flat-file
AS far as I know, I can't use the NSXMLParser for this task (because obviously there are no tags).
So I at first tried to programm a NSScanner which should get me the interesting properties --> didn't work out
Now I am using this method:
- (void) parseMemberDataWithURL: (NSString *)urlString
{
self.memberTempCounter = 1;
//Get data from web
self.downloadedText = [NSString stringWithContentsOfURL: [NSURL URLWithString: urlString] encoding:NSUTF8StringEncoding error:nil ];
memberArray = [downloadedText componentsSeparatedByString:#";"];
while (self.memberTempCounter<[memberArray count])
{
[[ExhibitorController sharedController] createExhibitorWithName:[memberArray objectAtIndex:self.memberTempCounter]
street:[memberArray objectAtIndex:self.memberTempCounter+2]
zip:[memberArray objectAtIndex:self.memberTempCounter+3]
city:[memberArray objectAtIndex:self.memberTempCounter+4]
email:[memberArray objectAtIndex:self.memberTempCounter+7]
phone:[memberArray objectAtIndex:self.memberTempCounter+5]
website:[memberArray objectAtIndex:self.memberTempCounter+8]
produktbereiche:[[memberArray objectAtIndex:self.memberTempCounter+9] componentsSeparatedByString:#","]];
self.memberTempCounter= self.memberTempCounter+13;
}
}
I am using the memberTempCounter to identify the property.
The problems are:
This only works out in like 3 of 4 times.1 of 4 times the App crashes and I have no Idea why...
The method has a performance like a 1962 VW Beetle. Parsing the whole chunk of data takes up to 3 Minutes on my iPhone 3G
Any Ideas or a simpler way to do this?
I would be really gratefull. Thanks in advance: -)
You might as well do all the parsing in the background, and then display as the information gets parsed.
As for memory issues, try doing temporary autorelease pools and release every 50 or so iterations through the loop.
int count = 0;
NSAutoreleasePool * loopPool = [[NSAutoreleasePool alloc] init];
while(someInsanelyLargeCondition){
// Do your stuff here
// .............
count++;
if (count > 50) {
count = 0;
[loopPool release];
loopPool = [[NSAutoreleasePool alloc] init];
}
}
Recursive-descent (LL1) parsers are pretty simple, light on memory, and for speed they go almost as fast as you can run a pointer through characters. Building your data structure would probably be the dominant time-taker.
I was finally able to fix my performance problem.
I have a method in another class, which ads Tags for the different Exhibitors. Therefore it first checks if the Tag already is stored in the database or else creates it.
With an growing Set of Tags in my database the search-process took longer and longer and this led to the long parsing time.
Anyone else having this problem: Take a look at the Performance Core Data Programming guide of apple in the "Implementing Find-or-Create Efficiently"-section:
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/CoreData/Articles/cdImporting.html

custom URL scheme doesn't work! Navigon AppInteract

It is really frustrating me. I used the doc provided by Navigon itself. Unfortunately it doesn't work as expected. Navigon launches, but stops at the main menu.
All I do is this:
NSString *myTestStr = [NSString stringWithFormat:#"navigon://App|Another place|FRA|75008|PARIS|rue de Turin|17|2.324621|48.881273"];
NSString *navigonStrEsc = [myTestStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"navigonStr: %#", navigonStrEsc);
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:navigonStrEsc]];
Any ideas what is wrong with my way?
thanks a lot!
Finally I figured out the right solution. The secret ingredients that the Navigon app interchanged the latitude and longitude values.
Use this custom url scheme to pass the navigation destination coordinates (the passed coordinates have to be on the loaded map):
navigon://coordinate/YourAppName/longitude/latitude
For example: navigon://coordinate/NaviCard/19.084443/47.573305
hum it should work. Here's my code:
The only diff is that my scheme changes if FRA is installed , then navigonFRA is prefered.
NSString* scheme = #"navigonFRA";
if ((![NavigonApplication isFRInstalled]) && [NavigonApplication isWorldInstalled])
scheme = #"navigon";
NSString* urlAsString = nil;
urlAsString = [NSString stringWithFormat:#"%#://%#|%#|%#|%#|%#|%#|%#|%f|%f",
scheme,
#"myApp", // Field1/AppName:Application or Company Name (e.g. AroundMe)
thePOI.name, // Field2/NameOfPOI: Name of POI (e.g. Navigon AG Würzburg)
#"FRA", // Field3/Country: ISO 3166-1 alpha-3 code for country (http://unstats.un.org/unsd/methods/m49/m49alpha.htm) (e.g. DEU)
#"", // Field4/ZipCode: Postalcode, ZIP code of the POIs city (e.g. 97080)
thePOI.location.city, // Field5/City: Name of POIs city (e.g. Würzburg)
thePOI.location.streetAddress, // Field6/Street:POIs street name (e.g. Berliner Platz)
#"", // Field7/HouseNumber: POIs street/house number (e.g. 11)
thePOI.location.longitude, // Field8/Longitude: Longitude in WGS84 (e.g. 9.870)
thePOI.location.latitude]; // Field9/Latitude: Latitude in WGS84 (e.g. 49.938)
urlAsString = [urlAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Starting Navigon app with %#", urlAsString);
NSURL*url = [[NSURL alloc] initWithString:urlAsString];
[[UIApplication sharedApplication ]openURL:url];
[url release];
And this code is working. Did you check that your navigon version is >= v1.5 ?
I found the problem, the first field (AppName) is pretty important.
The following html link now works :
Some nice place
For informations : I called the navigon support yesterday, the woman who answered was helpless and terribly aggressive, I'm thinking about using TomTom now :)