UI hang before Call back of SignalR - ios

Im using signalR for sending data here is my code to send data.
manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/json"];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
setUrl = [NSString stringWithFormat:#"%#%#",[UtilHelper sharedManager].WebServiceURL,#"Save"];
NSDictionary *parameters = [[NSDictionary alloc]initWithObjectsAndKeys:dicArray,#"products", nil];
__block NSMutableArray* json;
json = [[NSMutableArray alloc]init];
[manager POST:setUrl parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:&writeError];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:&writeError];
if ([[dic valueForKey:#"StatusMsg"] isEqualToString:#"Success"]) {
// save To S3 Bucket
[self sendPicture:[NSString stringWithFormat:#"%#",strProductId] : strPackageId];
[[results objectAtIndex:i] setValue:[NSNumber numberWithBool:YES] forKey:#"productsync"];
[[results objectAtIndex:i] setValue:[NSNumber numberWithBool:YES] forKey:#"editflag"];
[context save:nil];
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
Now im getting SignalR response in AppDelegate
[hubConnection setReceived:^(NSString *message) {
NSLog(#"%#",message);
});
When setReceived called my UI hand here is my code that i present my UIViewController that i present and hang UI init
-(void)handlePlusOption{
__weak __typeof(&*self)weakSelf = self;
dispatch_async( dispatch_get_main_queue(), ^{
__strong __typeof(&*weakSelf)strongSelf = weakSelf;
strongSelf.addProductVc = [[AddProductVC alloc] initWithNibName:addProductVcIdentifier bundle:nil];
strongSelf.nav = [[UINavigationController alloc] initWithRootViewController:strongSelf.addProductVc];
strongSelf.nav.modalPresentationStyle = UIModalPresentationFormSheet;
strongSelf.nav.modalTransitionStyle=UIModalTransitionStyleCoverVertical;
strongSelf.nav.modalPresentationCapturesStatusBarAppearance = NO; // To hide status bar, doest work with UIModalPresentationPageSheet style
[self.navigationController presentViewController:strongSelf.nav animated:YES completion:NULL];
});
}
Why UI hang before setReceived ?

try to put your setReceived block of code inside this block ..
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// time-consuming task
[hubConnection setReceived:^(NSString *message) {
NSLog(#"%#",message);
}];
dispatch_async(dispatch_get_main_queue(), ^{
// run in main thread
});
});

Related

Upload process blocks other requests AFNetworking 3.0

I am trying to upload data with AFNetworking and its successful. no problem with that but the problem is when I am doing it in background than the other requests blocks and doesn't give any response until upload progress finishes.
What I did is I made a singleton and declare AFURLSessionManager in that because I want all current running task.
+ (id)sharedInstance
{
static SharedManager *sharedMyManager = nil;
#synchronized(self) {
if (sharedMyManager == nil)
sharedMyManager = [[self alloc] init];
}
return sharedMyManager;
}
Let me tell you simple example.. for one controller, I made a request for upload process like below
ViewController1.m
-(void)postImage{
#try {
NSMutableDictionary *otherParameters = [[NSMutableDictionary alloc]initWithDictionary:_currentPlaceParameters];
[otherParameters setObject:[UtitlityManager getUserID] forKey:#"user_id"];
AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
NSMutableURLRequest *request =
[serializer multipartFormRequestWithMethod:#"POST" URLString:URL_UPLOAD_PHOTO_VIDEO parameters:otherParameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
NSData *thumbImageData = UIImageJPEGRepresentation(dataValue, 0.5);
[formData appendPartWithFileData:thumbImageData name:#"thumbnail" fileName:#"image.jpg" mimeType:#"image/jpeg"];
} error:nil];
//show progress bar on window
AFURLSessionManager *manager = [[SharedManager sharedInstance]manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
float uploadActualPercentage = uploadProgress.fractionCompleted * 100;
NSLog(#"Multipartdata upload in progress: %#",[NSString stringWithFormat:#"%f %%",uploadActualPercentage]);
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
} else {
NSDictionary *result=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
if([[result objectForKey:#"success"] integerValue]==1){
}else{
[Common showMessageWithMessage:#"Failed, Try again"];
}
}
}];
[uploadTask resume];
} #catch (NSException *exception) {
NSLog(#"EXC: %#",[exception description]);
}
}
And than I try to move another view controller and send a request for get other data ...
ViewController2.m
-(void)getData{
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSDictionary* responseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
} failure:^(NSURLSessionTask *operation, NSError *error) {
}];
}
But this doesn't give response until progress finishes... why so??
Even I try to set this upload process in dispatch_sync but it won't work ... any suggestion on this???

AFNetworking 3.0 Post Issues

I need the pros here to enlighten me on what's wrong with my code. I'm trying to migrate from 2.x to 3.x and I'm getting a migraine.
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSDictionary *parameters = #{#"email": email, #"password": password};
[manager POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSData *jsonData = [responseStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData
options:0
error:nil];
if ([[json objectForKey:#"success"] intValue] != 1) {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"" message:self.error_login delegate:nil cancelButtonTitle:self.continueButton otherButtonTitles:nil];
[MBProgressHUD hideHUDForView:self.view animated:YES];
[alert show];
} else {
[MBProgressHUD hideHUDForView:self.view animated:YES];
AccountViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:#"account"];
NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:[[self navigationController] viewControllers]];
[viewControllers removeLastObject];
[viewControllers addObject:vc];
[[self navigationController] setViewControllers:viewControllers animated:NO];
}
} failure:^(NSURLSessionDataTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
The server side keeps showing that the parameters are empty.
Any guidance would be greatly appreciated =D
the code for creating the post request is correct. tried it on my own server and it works as expected. so check that the values in email and password are not nil and also check your server code.
you can use a AFJSONSerializer to make your completion code a little easier though. then you do not have to convert the responseObject yourself since AFNetworking takes care of this:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *parameters = #{#"email": email, #"password": password};
[manager POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSDictionary *json = responseObject;
if ([[json objectForKey:#"success"] intValue] != 1) {
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"" message:self.error_login delegate:nil cancelButtonTitle:self.continueButton otherButtonTitles:nil];
[MBProgressHUD hideHUDForView:self.view animated:YES];
[alert show];
} else {
[MBProgressHUD hideHUDForView:self.view animated:YES];
AccountViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:#"account"];
NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:[[self navigationController] viewControllers]];
[viewControllers removeLastObject];
[viewControllers addObject:vc];
[[self navigationController] setViewControllers:viewControllers animated:NO];
}
} failure:^(NSURLSessionDataTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
AFNetworking 3.0 Post Method code.
Note :- Put this line in .h file.
+ (void)requestPostUrl: (NSString *)serviceName parameters:(NSDictionary *)dictParams success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure;
Note :- Put this code in .m file.
+ (void)requestPostUrl: (NSString *)serviceName parameters:(NSDictionary *)dictParams success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:error];
NSString *argString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
return argString;
}];
//here 'kBaseURL' is Web services base URL and servicesName is Web Services API name, You have to pass from declaration side.
NSString *strService = [NSString stringWithFormat:#"%#%#",kBaseURL,serviceName];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
//[SVProgressHUD showWithStatus:#"Please wait..."];
[SVProgressHUD show];
[manager POST:strService parameters:dictParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if([responseObject isKindOfClass:[NSDictionary class]]) {
if(success) {
[SVProgressHUD dismiss];
success(responseObject);
}
}
else
{
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
if(success) {
[SVProgressHUD dismiss];
NSLog(#"POST Response : %#",response);
success(response);
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
if(failure) {
[SVProgressHUD dismiss];
failure(error);
}
}];
}

AFNetworking Data Parameter is nil JSON Data

I have an UITableViewController and I'm trying getting JSON data from url with this code but I'm getting error.What should I do ?
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
NSString *urlPath = [NSString stringWithFormat:#"http://testurl.com/api/index.php"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"process":#"search_customer",#"page": #""};
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:urlPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSData *jsonData = [NSData dataWithContentsOfFile:string];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.customerCards = [NSMutableArray array];
NSArray *customersArray = [dataDictionary objectForKey:#"musteri_list"];
for (NSDictionary *customersDictionary in customersArray) {
ApiClass *customer = [ApiClass customersWithTitle:[customersDictionary objectForKey:#"adi"]];
customer.tel = [customersDictionary objectForKey:#"tel"];
[self.customerCards addObject:customer];
}
NSLog(#"GET: %#", string);
NSLog(#"POST: %#", parameters);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
This is the error bloc
2015-03-26 14:27:37.656 SaphiraCrm[13770:3881729] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
I think the problem could be in the fact that you are treating the responseObject as if it was NSData, but according to AFNetworking examples, by default AFHTTPRequestOperationManager's responseSerializer is an AFJSONResponseSerializer, so responseObject is already a parsed JSON represented as an NSDictionary (depends on the serializer).
Therefore, the line
NSString *string = [[NSString alloc] initWithData:responseObject
encoding:NSUTF8StringEncoding];
returns nil, which causes the next line
NSData *jsonData = [NSData dataWithContentsOfFile:string];
to raise the exception.
I would suggest that you check responseObject is what you expect it to be and refactor your code accordingly.
...
[manager POST:urlPath
parameters:parameters
success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (responseObject) {
NSLog(#"Response is a %# and contains: %#", [responseObject class], responseObject);
// Process responseObject according to its type
...
Note:
It is very likely that the above is just the consequence of a previous mistake in the way you set your seriliazer's configuration, since you set first the acceptableContentType first and then overwrite it with the default one.
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
...
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// this is likely to invalidate the previous, since you overwritting
// the manager's serializer with a new one with default configuration.
Okey I figured Out how can I do this.
There is my code
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
NSString *urlPath = [NSString stringWithFormat:#"http://test.com/api/index.php"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"process":#"search_customer",#"page": #""};
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:urlPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.customerCards = [NSMutableArray array];
NSArray *customersArray = [dataDictionary objectForKey:#"musteri_list"];
NSLog(#"%#",customersArray);
for (NSDictionary *customersDictionary in customersArray) {
ApiClass *customer = [ApiClass customersWithTitle:[customersDictionary objectForKey:#"adi"]];
customer.tel = [customersDictionary objectForKey:#"tel"];
[self.customerCards addObject:customer];
}
[self.tableView reloadData];
NSLog(#"GET: %#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

UISearchBar displaying data UITableView

I'm trying understand searchbar I have an api And when I send the api 'where' its giving me some data.
But when I tap the return key.I get nothing.
there is my code.
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
NSString *urlPath = [NSString stringWithFormat:#"http://test.com/api/index.php"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"process":#"search_record",#"where": self.searchBar.text};
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:urlPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.customerCards = [NSMutableArray array];
NSArray *customersArray = [dataDictionary objectForKey:#"customer_list"];
NSLog(#"%#",customersArray);
for (NSDictionary *customersDictionary in customersArray) {
ApiClass *customer = [ApiClass customersWithTitle:[customersDictionary objectForKey:#"adi"]];
customer.tel = [customersDictionary objectForKey:#"tel"];
[self.customerCards addObject:customer];
}
[self.tableView reloadData];
NSLog(#"GET: %#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
what should I do.
Thanks

Pagination in objective-c UITableViewController

I'm Trying to make pagination with this code.But When I scroll bottom its going 50-60 pages.
What I'm doing wrong.
NSInteger pagesNumber = 1;
- (void)api {
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
NSString *urlPath = [NSString stringWithFormat:#"http://test.com/api/index.php"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"process":#"search_customer",#"page": [NSString stringWithFormat:#"%d",pagesNumber]};
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:urlPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.customerCards = [NSMutableArray array];
NSArray *customersArray = [dataDictionary objectForKey:#"musteri_list"];
for (NSDictionary *customersDictionary in customersArray) {
ApiClass *customer = [ApiClass customersWithTitle:[customersDictionary objectForKey:#"adi"]];
customer.tel = [customersDictionary objectForKey:#"tel"];
NSLog(#"%#",customer.tel);
[self.customerCards addObject:customer];
}
[self.tableView reloadData];
NSLog(#"GET: %#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
And This is my scrollViewDidScroll method.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView_ {
if(self.tableView.contentOffset.y >= (self.tableView.contentSize.height - self.tableView.bounds.size.height))
{
pagesNumber = pagesNumber + 1;
[self api];
}
}
So I what should I do in this section.And When I scroll Up data is missing.Its showing currentPageData.
Thanks
Declaration:
NSInteger pagesNumber = 1;
Call "api" method from viewDidLoad, to load data:
- (void)api {
AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
[securityPolicy setAllowInvalidCertificates:YES];
NSString *urlPath = [NSString stringWithFormat:#"http://test.com/api/index.php"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"process":#"search_customer",#"page": [NSString stringWithFormat:#"%d",pagesNumber]};
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager setSecurityPolicy:securityPolicy];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:urlPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.customerCards = [NSMutableArray array];
NSArray *customersArray = [dataDictionary objectForKey:#"musteri_list"];
for (NSDictionary *customersDictionary in customersArray) {
ApiClass *customer = [ApiClass customersWithTitle:[customersDictionary objectForKey:#"adi"]];
customer.tel = [customersDictionary objectForKey:#"tel"];
NSLog(#"%#",customer.tel);
[self.customerCards addObject:customer];
}
[self.tableView reloadData];
NSLog(#"GET: %#", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
//instead of using scrollViewDidScroll better use willDisplayCell:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
if(self.customerCards.count>1){
if(indexPath.row == self.customerCards.count-1){
pagesNumber=pagesNumber+1;
[self api];
}
}
}

Resources