PLCrashReporter always returns no crash log - ios

I'm trying to capture crash log using PLCrashReporter and send it via webservice on next App launch.
Code :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//[self checkChrash];
PLCrashReporter *crashReporter = [PLCrashReporter sharedReporter];
BOOL value = [crashReporter hasPendingCrashReport];
if (value)
[self handleCrashReport];
BOOL val= [crashReporter enableCrashReporterAndReturnError:nil];
return YES;
}
#pragma mark - Crash Reports
- (void)handleCrashReport
{
PLCrashReporter *crashReporter = [PLCrashReporter sharedReporter];
NSData *crashData;
NSError *error;
crashData = [crashReporter loadPendingCrashReportDataAndReturnError:&error];
PLCrashReport *report = [[PLCrashReport alloc] initWithData:crashData error:nil];
if (!crashData || !report) {
[crashReporter purgePendingCrashReport];
} else {
NSString *stringRepresentation = [PLCrashReportTextFormatter stringValueForCrashReport:report withTextFormat:PLCrashReportTextFormatiOS];
[self sendDataOnLatestCrashToServer:stringRepresentation];
[crashReporter purgePendingCrashReport];
}
}
- (void)sendDataOnLatestCrashToServer:(NSString *)crashString
{
/* NSDictionary *params = #{
#"StackTrace" : crashString
// Add more parameters as you want
};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil];
NSURL *url = [NSURL URLWithString:#"http://www.YOURRESTSERVER.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0f];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
}];
*/
}
I'm always getting return of hasPendingCrashReport as NO. I made the App crash using following :
assert(0);
NSArray * arr = [[NSArray alloc] init];
[arr objectAtIndex:10];
Please help me with this, thanks in advance

Related

How to convert this get method into post?

Below is the code. It's using GET method for parsing and request.
- (void)getStudentsWithOptions:(NSString*)getURLString screen:(NSString *)screenString completion:(SkoolBeepCompletion)completion {
if (!completion) return;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:getURLString]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
completion(nil, error);
} else {
NSError *err = nil;
NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
//NSLog(#"dataDict : %#", dataDict);
if (!err) {
if ([screenString isEqualToString:#"My Students"]) {
[CoreDataController deleteAllObjects:#"Students"];
NSDictionary *dicEntry = [dataDict objectForKey:#"return_arr"];
for (NSDictionary *dicInsert in dicEntry) {
[CoreDataController storeStudentsObjects:dicInsert];
[CoreDataController storeChildrenObjects:dicInsert];
}
completion(dataDict, nil);
} else if ([screenString isEqualToString:#"User Settings"]) {
[CoreDataController deleteAllObjects:#"Profile"];
[CoreDataController storeProfileObjects:dataDict];
completion(dataDict, nil);
} else if ([screenString isEqualToString:#"About"]) {
[CoreDataController deleteAllObjects:#"About"];
[CoreDataController storeAboutObjects:dataDict];
completion(dataDict, nil);
} else if ([screenString isEqualToString:#"Works"]) {
[CoreDataController deleteAllObjects:#"Works"];
[CoreDataController storeWorksObjects:dataDict];
completion(dataDict, nil);
} else {
completion(dataDict, nil);
}
} else {
completion(nil, err);
}
}
}];
}
Above is line of code that I want in POST.
URLRequest must be using POST type.
I have added the code in my question.
Use NSMutableURLRequest for POST
NSString *Post=[NSString stringWithFormat:#"email=%#&password=%#",#"iamiosguy#gmail.com",#"lovetocode"];
NSData *PostData = [Post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *PostLengh=[NSString stringWithFormat:#"%d",[Post length]];
NSURL *Url=[NSURL URLWithString: #"Your URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:Url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:PostLengh forHTTPHeaderField:#"Content-Lenght"];
[request setHTTPBody:PostData];
NSData *ReturnData =[NSURLConnection sendSynchronousRequest:request returningResponse:Nil error:Nil];
NSString *Response = [[NSString alloc] initWithData:ReturnData encoding:NSUTF8StringEncoding];
NSLog(#"Response%#",Response);

iOS - different response from single API in ARC and parsing

In my project i am passing this API: http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat with params: prod_id=25,var_id=140.
The problem is when i am pass this api in Rest Client it displays correct response but when i am trying to put it in my code it shows different response.
i am using the following code:
-(void)listofNotice
{
NSString *post = [NSString stringWithFormat:#"prod_id=25,var_id=140"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
//NSLog(#"str : %#",str);
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
}
- (id)cleanJsonToObject:(id)data
{
NSError* error;
if (data == (id)[NSNull null])
{
return [[NSObject alloc] init];
}
id jsonObject;
if ([data isKindOfClass:[NSData class]])
{
jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
else
{
jsonObject = data;
}
if ([jsonObject isKindOfClass:[NSArray class]])
{
NSMutableArray *array = [jsonObject mutableCopy];
for (int i = (int)array.count-1; i >= 0; i--)
{
id a = array[i];
if (a == (id)[NSNull null])
{
[array removeObjectAtIndex:i];
} else
{
array[i] = [self cleanJsonToObject:a];
}
}
return array;
}
else if ([jsonObject isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictionary = [jsonObject mutableCopy];
for(NSString *key in [dictionary allKeys])
{
id d = dictionary[key];
if (d == (id)[NSNull null])
{
dictionary[key] = #"";
} else
{
dictionary[key] = [self cleanJsonToObject:d];
}
}
return dictionary;
}
else
{
return jsonObject;
}
}
it display the following response:
str : {
business = 0;
"business-list" = "Business list empty.";
response = 401;
}
but the actual response is something like this
please help me.. Thanks In advance
Please change this
NSString *post = [NSString stringWithFormat:#"prod_id=25,var_id=140"];
To:
NSString * post =[NSString stringWithFormat:#"prod_id=25&var_id=140"];
if possible use this:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.HTTPAdditionalHeaders = #{#"application/x-www-form-urlencoded" : #"Content-Type"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [post dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (data != nil){
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger code = [httpResponse statusCode];
NSLog(#"Status Code: %ld", (long)code);
if (code == 200) {
NSError *error;
id responseObject =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
}
}
}];
[postDataTask resume];
OR
NSString *postString = [NSString stringWithFormat:#"prod_id=%#&var_id=%#",#"25",#"140"];
NSURL *urlPath = [NSURL URLWithString:#"http://dev-demo.info.bh-in-15.webhostbox.net/dv/nationalblack/api/businessbysubcat"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlPath
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
NSData *requestData = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
[APP_DELEGATE removeLoader];
if(data != nil) {
NSDictionary *responseObject =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSLog(#" %#", responseObject);
}
else {
}
}];
Hope this helps.
I think you need to change below code
NSString *post = [NSString stringWithFormat:#"prod_id=25,var_id=140"];
to
NSDictionary *prodDict=#{#"prod_id":#"25",
#"var_id":#"140"};

Run multiple urls to get multiple JSON values

I need to get a single value of JSON data from from four urls each. The code i've written to get JSON data from single url is
NSString *url=[NSString stringWithFormat:#"http://jsondata.in/UserImage.svc/GetUnAnsweredImagesLogCount?UserId=%#",requestString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"GET"];
NSURLConnection * connReq = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if (connReq) {
NSLog(#"Connection Sucessful");
receivedData = [[NSMutableData alloc]init];
[self facialimagelogcounturl];
}
else
{
NSLog(#"failed");
}
[connReq start];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Status code: %ld", (long)[response statusCode]);
NSLog(#"respdata%#",respData);
-(void)connection:(NSURLConnection *)connection didReceiveResponse:
(NSURLResponse *)response
{
[receivedData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:
(NSData *)data
{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"ERROR");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *e;
NSString *JSON = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
_userlogcountlabel.text=JSON;
int json=[JSON intValue];
}
I need to display the data in different labels each for a url.For single getting single value from a single url its working fine. I need to make it for multiple urls.
Here is the answer for my own question.
NSString *url1=[NSString stringWithFormat:#"http://jsonddata.in/UserImage.svc/GetNotificationCount?UserId=%#&CategoryId=1",requestString];
NSURL *URL1 = [NSURL URLWithString:url1];
NSMutableURLRequest *request1 = [[NSMutableURLRequest alloc] initWithURL:URL1] ;
[NSURLConnection sendAsynchronousRequest:request1 queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSArray *results1 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"facialimage log count %#",[results1.firstObject objectForKey:#"Notifications"]);
}];
NSString *url2=[NSString stringWithFormat:#"http://jsonddata.in/UserImage.svc/GetNotificationCount?UserId=%#&CategoryId=2",requestString];
NSURL *URL2 = [NSURL URLWithString:url2];
NSMutableURLRequest *request2 = [[NSMutableURLRequest alloc] initWithURL:URL2] ;
[NSURLConnection sendAsynchronousRequest:request2 queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSArray *results1 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"clothing log count %#",[results1.firstObject objectForKey:#"Notifications"]);
}];
NSString *url3=[NSString stringWithFormat:#"http://jsondata.in/UserImage.svc/GetNotificationCount?UserId=%#&CategoryId=3",requestString];
NSURL *URL3 = [NSURL URLWithString:url3];
NSMutableURLRequest *request3 = [[NSMutableURLRequest alloc] initWithURL:URL3] ;
[NSURLConnection sendAsynchronousRequest:request3 queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSArray *results1 = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"object compare log count %#",[results1.firstObject objectForKey:#"Notifications"]);
}
}];

An asynchronous nsurlconnection in a popup view in ios7

I am creating an asynchronous NSURLconnection in a popup view in ios.
To implement the asynchronous NSURLconnection I implement the methods of the NSURLDelegate.
The problem occurs when the user taps outside the popup view and the view is dismissed.
leaving the nsurlconnection callbacks and other actions inside the view incomplete.
How can I assure that the actions inside the popup complete inspite of the dismissal of the view?
I tried putting an activity indicator inside the popup view till the actions are completed, but even then a tap outside the popup view dismisses the view.
I dont want the user to be left with an inactive app till actions are completed, instead I want the actions to be completed in the background.
If you want to send an asynchronous connection you can use this methods.
GET REQUEST
-(void)placeGetRequest:(NSString *)action withHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *error))ourBlock {
NSString *url = [NSString stringWithFormat:#"%#/%#", URL_API, action];
NSURL *urlUsers = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:urlUsers];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
}
POST REQUEST
-(void)placePostRequest:(NSString *)action withData:(NSDictionary *)dataToSend withHandler:(void (^)(NSURLResponse *response, NSData *data, NSError *error))ourBlock {
NSString *urlString = [NSString stringWithFormat:#"%#/%#", URL_API, action];
NSLog(urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Creamos el JSON desde el data
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dataToSend options:0 error:&error];
NSString *jsonString;
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSData *requestData = [NSData dataWithBytes:[jsonString UTF8String] length:[jsonString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:ourBlock];
}
}
EXAMPLE OF USE
- (void) getMyMethod:(NSString *)myParam1
myParam2:(NSString *)myParam2
myParam3:(NSString *)myParam3
calledBy:(id)calledBy
withSuccess:(SEL)successCallback
andFailure:(SEL)failureCallback{
[self placeGetRequest:[NSString stringWithFormat:#"api/myMethod?myParam1=%#&myParam2=%#&myParam3=%#",myParam1, myParam2, myParam3]
withHandler:^(NSURLResponse *response, NSData *rawData, NSError *error) {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSInteger code = [httpResponse statusCode];
NSLog(#"%ld", (long)code);
if (code == 0){
// error
} else if (!(code >= 200 && code < 300) && !(code == 500)) {
NSString *string = [[NSString alloc] initWithData:rawData
encoding:NSUTF8StringEncoding];
NSLog(#"ERROR (%ld): %#", (long)code, string);
[calledBy performSelector:failureCallback withObject:string];
} else {
// If you receive a JSON
NSMutableDictionary *result = [NSJSONSerialization JSONObjectWithData:rawData options:0 error:nil];
// If you receive an Array
// NSArray *result = [NSJSONSerialization JSONObjectWithData:rawData options:0 error:nil];
// If you receive a string
// NSString *result = [[NSString alloc] initWithData:rawData encoding:NSUTF8StringEncoding];
[calledBy performSelector:successCallback withObject:result];
}
}];
}
CALL YOU MUST DO IN YOUR VIEW/CONTROLLER/ETC
(...)
[api getMyMethod:myParam1Value myParam2:myParam2Value myParam3:myParam3Value calledBy:self withSuccess:#selector(getMyMethodDidEnd:) andFailure:#selector(getMyMethodFailureFailure:)];
(...)
// Don't forget to set your callbacks functions or callbacks will do your app crash
-(void)getMyMethodDidEnd:(id)result{
// your actions with the result
// ...
}
-(void)getMyMethodFailure:(id)result{
// your actions with the result
// ...
}
To prevent the dismissal of popup view when tapping out side u need to implement this delegate method
- (BOOL)popoverControllerShouldDismissPopover:(UIPopoverController *)popoverController
{
return NO;
}
dismiss it by using the action
- (void)someAction
{
//check the operations are completed
.....
.....
[popoverController dismissPopoverAnimated:YES];
}

stringWithContentsOfUrl in background

UPDATE: Here's all the file's I'm using in my github repo. Perhaps it will help more than my code snippets:
appDelegate
mainViewController
calendarHandler
NSString* result = [NSString stringWithContentsOfURL:urlRequest encoding:NSUTF8StringEncoding error:&err];
That's the line I'm using in my project to get data from a website. I run this in an NSOperationQueue and when I run with my app in the foreground, it works without issue. However I also have my app set to run in the background using performFetchWithCompletionHandler. All of my setup code works fine using the performFetch, but when it hits the line I've outlined above, the app just hangs until I bring my app into the foreground again.
How can I let this work in the background?
In my AppDelegate I have performFetchWithCompletionHandler:
- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
UINavigationController *navigationController = (UINavigationController*) self.window.rootViewController;
id topViewController = navigationController.topViewController;
if ([topViewController isKindOfClass:[ViewController class]])
{
[(ViewController*)topViewController autoLogin];
}
completionHandler(UIBackgroundFetchResultNewData);
}
My NSOperationQueue is built like this in my MainViewController:
- (void) autologin
{
NSOperationQueue* backgroundQueue = [NSOperationQueue new];
ch = [[myEventHandler alloc] init];
NSInvocationOperation* operation = [[NSInvocationOperation alloc] initWithTarget:ch selector:#selector(runEvents:) object:login];
[backgroundQueue addOperation:operation];
}
And in MyEventHandler I have runEvents
- (void) runEvents
{
NSURL* urlRequest = [NSURL URLWithString:#"http://www.google.com"];
NSError* err = nil;
NSString* result = [NSString stringWithContentsOfURL:urlRequest encoding:NSUTF8StringEncoding error:&err];
}
Try with This code:
NSString *urlString=[NSString stringWithFormat:#"%#listcontact.php?uid=%#&page=0",LocalPath,appdel.strid];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSError *error1;
NSDictionary *res=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error1];
}];
have you tried using NSURLConnection (asynchronous) instead of stringWithContentsOfURL (synchronous)?
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://google.com"]];
[NSURLConnection sendAsynchronousRequest:request queue: [NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSString *theResult = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// blah blah
}];

Resources