Use of activity indicator in json parsing - ios

I am working on application and i have to use activityindicator when login is in progress, i am not getting where i have to use the code for activityindicator in the below code:-
- (IBAction)Login:(id)sender
{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl#"login"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"userName=g&userPassword=123456&api_key=ZWZ&api_password=1" ];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"text= %#",text);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
It is taking time to go the other page after login.
please help me.

Use this below code
//main thread
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinner.center = CGPointMake([[UIScreen mainScreen]bounds].size.width/2, [[UIScreen mainScreen]bounds].size.height/2);
//if you want to add to window, use this below one
[appdelegate.window addSubview:spinner];
//or if you want to add to view, use below one
[self.view addSubView:spinner];
[spinner startAnimating];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),^{
dispatch_async(dispatch_get_main_queue(), ^{
//after your server call or parsing or something you can call this to stop animating
[spinner stopAnimating];
});
});

aakash,
You can make use of MBProgressHUD third party framework you need not write the code for activity inddicator adding it to screen and all (no need to re invent the wheel) here is a link :) https://github.com/jdg/MBProgressHUD
add a pod dependency or add the files to your project however you feel comfortable.
import files.
#import <MBProgressHUD/MBProgressHUD.h>
- (IBAction)Login:(id)sender
{
//add the MBProgressHud here before you make the webservice call
MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
hud.labelText = NSLocalizedString(#"Login in progress", nil);
[self.navigationController.view addSubview:self.HUD];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl#"login"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"userName=g&userPassword=123456&api_key=ZWZ&api_password=1" ];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
//finally hide it, whether its sucess or failure just remove it
[MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
});
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"text= %#",text);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}

I have updated code for Activity indicator.
Just make the outlet of the Activity Indicator in .h file.
#property (weak,nonatomic) UIActivityIndicatorView *indicator;
then, write below code in .m file's viewDidLoad().
self.indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
self.indicator.center = CGPointMake([[UIScreen mainScreen]bounds].size.width/2, [[UIScreen mainScreen]bounds].size.height/2);
Below is the code for Json parsing:
- (IBAction)Login:(id)sender
{
[self.indicator startAnimating];//The ActivityIndicator Starts Animating Here
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl#"login"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"userName=g&userPassword=123456&api_key=ZWZ&api_password=1" ];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.indicator stopAnimating];//The ActivityIndicator Stops Animating when Response Arrives
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"text= %#",text);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
[self checkUserSuccessfulLogin:json];
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.indicator stopAnimating];
});
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}

- (IBAction)Login:(id)sender
{
//show or add youar activity indicator here
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl#"login"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"userName=g&userPassword=123456&api_key=ZWZ&api_password=1" ];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Hide or remove your activity indicator here
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"text= %#",text);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
As i add comments in your code, show your activity indicator at very start of method as user tap button it starts and hide it from completion handler because completion handler calls after response is came from server.
Hope this will help :)

Try This Code
-(IBAction)Login:(id)sender
{
UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
CGRect activityFrame = CGRectMake(130,10,40,40);
[activityView setFrame: activityFrame];
dispatch_async(dispatch_get_main_queue(), ^{
[self.view addSubview:activityView];
activityView.center = self.view.center;
[activityView startAnimating];
[self.view bringSubviewToFront:activityView];
});
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:BaseUrl#"login"]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"userName=g&userPassword=123456&api_key=ZWZ&api_password=1" ];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"text= %#",text);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[activityView stopAnimating];
[activityView removeFromSuperview];
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}

Related

I want to upload image with other parameters to server using objective c

well am new to iOS and i encountered a situation where i have to upload a image to server. Here is what am doing in the post method.
- (IBAction)submitClicked:(UIButton *)sender {
NSDictionary *inputData = [NSDictionary dictionaryWithObjectsAndKeys:myImage,#"coverPic", nil];
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://api.mapartment.in/index.php/events/create"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:70.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSData *jsonInputData = [NSJSONSerialization dataWithJSONObject:inputData options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonInputData encoding:NSUTF8StringEncoding];
[request setHTTPBody:[jsonInputString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary *jsondictcity_name = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
if([[jsondictcity_name valueForKey:#"result"] isEqual:#"true"]){
NSLog(#"Success");
}
else{
NSLog(#"Try Again");
}
[self.view resignFirstResponder];
});
}
];
[postDataTask resume];
}
P.S. _localFilePath contains - /Users/appcode/Library/Developer/CoreSimulator/Devices/3C3567B8-03BC-4233-B0BC-97E3899D0AAA/data/Containers/Data/Application/3D574024-42FB-4305-807A-ACC3C128383F/Documents/png
Image will not pass with other parameter,you have to convert image into NSData
UIImage *yourImage= [UIImage imageNamed:#"image.png"];
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *postLength = [NSString stringWithFormat:#"%d", [imageData length]];
and then pass these data in request
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:imageData];
and other parameter pass as json.
to get UIImage from path use
UIImage *yourImage = [UIImage imageWithContentsOfFile: imageFilePath];
- (IBAction)submitClicked:(UIButton *)sender {
UIImage* image = [UIImage imageWithContentsOfFile:_localFilePath];
NSString *myImage = [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSDictionary *inputData = [NSDictionary dictionaryWithObjectsAndKeys:myImage,#"coverPic",#"POEM WRITING",#"title",#"Bring your own paper",#"desc", nil];
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://api.mapartment.in/index.php/events/create"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:70.0];
[request addValue:#"multipart/form-data" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSData *jsonInputData = [NSJSONSerialization dataWithJSONObject:inputData options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonInputData encoding:NSUTF8StringEncoding];
[request setHTTPBody:[jsonInputString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary *jsondictcity_name = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
if([[jsondictcity_name valueForKey:#"result"] isEqual:#"true"]){
NSLog(#"Success");
}
else{
NSLog(#"Try Again");
}
[self.view resignFirstResponder];
});
}
];
[postDataTask resume];
}

How to integrate rest API using NSURLConnection in iOS?

I have tried this methods, I want to know about integration of rest API in iOS.
I want to know about JSON parsing in web services. I know about these methods but how to use it? but what is function of each method?
This IBAction method sends request string for signup to the server .
-(void)genSignup
{
responseData = [NSMutableData data];
urlLoc= [urlLoc stringByAppendingString:service];
NSLog(#"%#",requestString);
NSData *postData = [requestString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlLoc]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//NSLog(#"%#",request);
PostConnectionRegisterGenUser = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[MyClass removePregressIndicator:self.view];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[MyClass removePregressIndicator:self.view];
if (connection == PostConnectionRegisterGenUser)
{
NSError *error;
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"%#",results);
}
}
how to use it?
NSURLConnection is deprecated effective Mac OS 10.11 and iOS 9. So, at this point NSURLSession should be used instead of NSURLConnection.
I just add NSURLSession in your code. Change Key, URL accordingly. I did not compile it.
NSString * requestString = [NSString stringWithFormat:#"Name=%#&Email=%#&Password=%#&MobileNumber=%#&BloodGroup=%#&DeviceID=%#&City=%#&DeviceType=I",txtName.text,txtEmail.text,txtPassword.text,txtMobileno.text,strBlood,strDeviceID,txtCity.text];
NSData *postData = [requestString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlLoc]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = #{ #"api-key": #"API_KEY"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSURLSessionDataTask *sessionPostDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// The server answers with an error because it doesn't receive the params
}];
[sessionPostDataTask resume];
Do let me know if you need any other information.
Hope this will help you !!!
Use simple common methods for NSURLSession WS Calling.
-(void)callWebserviceWithParams:(NSDictionary *)aParams withURL:(NSString *)aStrURL withTarget:(UIViewController *)aVCObj withCompletionBlock:(void(^)(NSMutableDictionary *aMutDict))completionBlock withFailureBlock:(void(^)(NSError *error))failure
{
NSString *aStrParams = [self getFormDataStringWithDictParams:aParams];
NSData *aData = [aStrParams dataUsingEncoding:NSUTF8StringEncoding];
aStrURL = [aStrURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *aRequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:aStrURL]];
[aRequest setHTTPMethod:#"POST"];
[aRequest setHTTPBody:aData];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
[aRequest setHTTPBody:aData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:aRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//
if (error ==nil) {
NSString *aStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"ResponseString:%#",aStr);
NSMutableDictionary *aMutDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
aMutDict = [aMutDict dictionaryByReplacingNullsWithBlanks];
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(aMutDict);
});
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
failure(error);
});
}
}];
[postDataTask resume];
}
-(NSString *)getFormDataStringWithDictParams:(NSDictionary *)aDict
{
NSMutableString *aMutStr = [[NSMutableString alloc]initWithString:#""];
for (NSString *aKey in aDict.allKeys) {
[aMutStr appendFormat:#"%#=%#&",aKey,aDict[aKey]];
}
NSString *aStrParam;
if (aMutStr.length>2) {
aStrParam = [aMutStr substringWithRange:NSMakeRange(0, aMutStr.length-1)];
}
else
aStrParam = #"";
return aStrParam;
}
Use Like This
NSDictionary* param = #{
#"Key1":#"Value1",
#"Key2":#"value2"
};
[self callWebserviceWithParams:param withURL:#"URL String" withTarget:self withCompletionBlock:^(NSMutableDictionary *aMutDict) {
//code For Success
} withFailureBlock:^(NSError *error) {
// code for WS Responce failure
}];
also you have to set this method in NSObject Class and make it simple and used in whole app.
Another option Nsurlsession:
-(void)Fetchdata
{
NSURLSessionConfiguration *defaultSessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultSessionConfiguration];
// Setup the request with URL
NSURL *url = [NSURL URLWithString:#"http://52.2/category_list.php"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
// Convert POST string parameters to data using UTF8 Encoding
NSString *postParams = #"admin_id=19";
NSData *postData = [postParams dataUsingEncoding:NSUTF8StringEncoding];
// Convert POST string parameters to data using UTF8 Encoding
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:postData];
// Create dataTask
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#",results);
arryTempdata = [[results valueForKey:#"message"] valueForKey:#"banner"];
NSLog(#"%#",arryTempdata);
tblV.reloadData;
}];
// Fire the request
[dataTask resume];
}

How to solve warning message: Sending 'viewController const __strong to parameter of incompatible type 'id<nsurlsessiondelegate>

The following code gave a warning of :
Sending 'viewController const __strong to parameter of incompatible
type 'id
Here is my code:
- (void)postRequestWithParam: (NSDictionary *)param onCompletion: (CompletionHandler)completionHandler
{
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.timeoutIntervalForRequest = 30.0;
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString: #"http://test.demo.net/demoapp/index.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
if(param == nil)
param = [NSDictionary dictionary];
NSData *postData = [NSJSONSerialization dataWithJSONObject:param options:0 error:&error];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if (!error)
{
completionHandler(YES, [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error], nil);
NSString *responseStr = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"res...%#",responseStr);
NSLog(#"RESPONSE: %#", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]);
}
else
{
completionHandler(NO, nil, error);
}
}];
[postDataTask resume];
}
Confirm <NSURLSessionDelegate> in your header file and it will solve the issue i think,
#interface ViewController : UIViewController <NSURLSessionDataDelegate>
It is because you are setting delegate to self in NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; So it's requires to confirm NSURLSessionDataDelegate protocol.

Rest call from webViewDidFinishLoad cause error

When i call getProfile method from viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
[self getProfile];
}
it success
-(void)getProfile
{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSString *tempurl= [NSString stringWithFormat:#"%#11155/person/#self",baseUrlSecure];
tempurl = [tempurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:tempurl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:gWCToken forHTTPHeaderField:#"WCToken"];
[request addValue:gWCTrustedToken forHTTPHeaderField:#"WCTrustedToken"];
[request setHTTPMethod:#"GET"];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error)
{
NSLog(#"Error: %#", error);
dispatch_async(dispatch_get_main_queue(), ^{
[Alert showAlertWithTitle:#"M2All" andWithMessage:error.localizedDescription onView:self andErrorCode:[NSString stringWithFormat:#"%ld",error.code]];
});
}
else
{
NSDictionary *dictResult = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *arrError = [dictResult objectForKey:#"errors"];
if(arrError.count >0)
{
dispatch_async(dispatch_get_main_queue(), ^{
[Alert showAlertWithTitle:#"M2All" andWithMessage:[[arrError objectAtIndex:0] objectForKey:#"errorMessage"] onView:self andErrorCode:[[arrError objectAtIndex:0] objectForKey:#"errorCode"]];
});
return;
}
}
}];
[postDataTask resume];
}
but same calling from webViewDidFinishLoad then getting error
i don't know what is the problem
- (void)webViewDidFinishLoad:(UIWebView *)webView{
[self getProfile];
}
Clear the browser cookies and try again. I faced the similar problem. I cleared the browser cache and it's working fine for me

how to handle response in json

I'm using this piece of code for hit data in url.
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request1 setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"company_name", _CompanyName.text,
#"email_id", _Email.text,#"password", _Password.text,nil];
NSLog(#"Result: %#",request1);
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request1 setHTTPBody:postData];
NSURLResponse *response = nil;
// NSError *error = nil;
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request1 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
NSLog(#"Result: %#",mapData);
NSLog(#"Result: %#",request1);
NSLog(#"Result: %#",data);
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Result: %#",dictionary);
NSLog(#"Result error : %#",error.description);
}];
[postDataTask resume];
value of uitextfield is not store in url when i clicked on button, what should i do here?
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"http://dev1.brainpulse.org/quickmanhelp/webservice/api.php?act=registration"];
NSMutableURLRequest *request1 = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request1 addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request1 setHTTPMethod:#"POST"];
//NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: _CompanyName.text,#"company_name",
//_Email.text,#"email_id", _Password.text,#"password",nil];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"yyyyy",#"company_name",
#"karthik.saral#gmail.com",#"email_id", #"XXXXX",#"password",nil];
NSLog(#"Result: %#",request1);
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request1 setHTTPBody:postData];
NSURLResponse *response = nil;
// NSError *error = nil;
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request1 completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
//Handle your response here
NSLog(#"Result: %#",mapData);
NSLog(#"Result: %#",request1);
NSLog(#"Result: %#",data);
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Result: %#",dictionary);
NSLog(#"Result error : %#",error.description);
NSLog(#"answewrv : %#",dictionary);
NSLog(#"Result error : %#",error.description);
}];
[postDataTask resume];
this is updated code after the amendments. i am getting the same error.
You are wrong here:
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"company_name", _CompanyName.text,
#"email_id", _Email.text,#"password", _Password.text,nil];
It should be
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: _CompanyName.text,#"company_name",
_Email.text,#"email_id", _Password.text,#"password",nil];
initWithObjectsAndKeys mean: object,key, object, key
I have done also this type work you can see this , may be it will help you.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#" your URL "];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"*/*" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *mapData = [NSString stringWithFormat:#"username=%#&password=%#&api_key=Your key", usernameField.text,passwordField.text];
NSData *postData = [mapData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
[request setHTTPBody:postData];
NSLog(#"%#", mapData);
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if(error!=nil)
{
NSLog(#"error = %#",error);
}
dispatch_async(dispatch_get_main_queue(), ^{
[self checkUserSuccessfulLogin:json];
});
}
else{
NSLog(#"Error : %#",error.description);
}
}];
[postDataTask resume];
}
- (void)checkUserSuccessfulLogin:(id)json
{
// NSError *error;
NSDictionary *dictionary = (NSDictionary *)json;
if ([[dictionary allKeys] containsObject:#"login"])
{
if ([[dictionary objectForKey:#"login"] boolValue])
{
[self saveLoginFileToDocDir:dictionary];
ItemManagement *i = [[ItemManagement alloc]init];
[self presentViewController:i animated:YES completion:Nil];
}
else
{
NSLog(#"Unsuccessful, Try again.");
UIAlertView *alertLogin = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Wrong Username Or Password" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[alertLogin show];
}
}
}
- (void)saveLoginFileToDocDir:(NSDictionary *)dictionary
{
NSArray *pListpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *pListdocumentsDirectory = [pListpaths objectAtIndex:0];
NSString *path = [pListdocumentsDirectory stringByAppendingPathComponent:#"Login.plist"];
BOOL flag = [dictionary writeToFile:path atomically:true];
if (flag)
{
NSLog(#"Saved");
}
else
{
NSLog(#"Not Saved");
}
}

Resources