Trying to understand asynchronous calls - ios

I have this method
- (NSString*) createUserWithName:(NSString*)TheName
{
NSURL *URL =someUrlthatIncludesTheName
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sharedSession];
NSURL *URL = [NSURL URLWithString:url];
NSURLSessionTask *task = [session dataTaskWithURL:URL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (response) {
NSError* error = nil;
NSArray *output = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
myID = [[output objectAtIndex:0] objectForKey:#"UserID"];
}
}];
[task resume];
return myID;
}
and another method
-(void)doSomethingWith: (NSString*) anID
Somewhere in my code, I call these methods subsequently, like this:
[self createUserWithName:#"John"];
[self doSomethingWith:myID];
However, due to the fact that the NSURLSession in createUserWithName: is asynchronous, doSomethingWith: is fired with myID = (null).
What is the best way to approach this problem, without necessarily falling back to deprecated synchronous NSURLConnection?
Thanks in advance

The workflow is supposed to be
- (void)createUserWithName:(NSString*)TheName
{
NSURL *URL =someUrlthatIncludesTheName
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sharedSession];
NSURL *URL = [NSURL URLWithString:url];
NSURLSessionTask *task = [session dataTaskWithURL:URL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (response) {
NSError* error = nil;
NSArray *output = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
myID = [[output objectAtIndex:0] objectForKey:#"UserID"];
[self doSomethingWith:myID];
}
}];
[task resume];
}
And the call is just
[self createUserWithName:#"John"];
The method doSomethingWith: is asynchronously executed in the completion block.
Alternatively use a custom completion block
- (void)createUserWithName:(NSString *)theName completion:^(NSString *identifier)completion
{
NSURL *URL =someUrlthatIncludesTheName
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"GET"];
NSURLSession *session = [NSURLSession sharedSession];
NSURL *URL = [NSURL URLWithString:url];
NSURLSessionTask *task = [session dataTaskWithURL:URL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (response) {
NSError* error = nil;
NSArray *output = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
myID = [[output objectAtIndex:0] objectForKey:#"UserID"];
completion(myID);
}
}];
[task resume];
}
and call it with
[self createUserWithName:#"John" completion:^(NSString *identifier) {
[self doSomethingWith:identifier];
}];

Related

Got Null Value From the api in objective c

I am fetching JSON values from the API...but it showing the values as null... I checked it in the postman it's working there and I have the response...I have listed my sample code below please mention my mistakes. I'm new to this development
- (IBAction)PaymentButtonTapped:(id)sender {
[self PayuMoneyAdminValues];
}
-(void)PayuMoneyAdminValues{
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]init];
NSString *urlstring = [NSString stringWithFormat:#"%#admindatas",restSiteURLServices];
NSURL *url = [NSURL URLWithString:urlstring];
NSString *userUpdate = [NSString stringWithFormat:#"%#",restAuth];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setURL:url];
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//NSData *data1 = [NSData dataWithContentsOfURL:url];
//Apply the data to the body
[urlRequest setHTTPBody:data1];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if(data!=nil){
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
if (parseError) {
NSLog(#"Admin data: %#",responseDictionary);
}
}
}];
[dataTask resume];
}

After using dispatch async in google maps route is not updating on the Simulator

I am trying to draw the route between two points on the maps.
I am using dispatch_sync to update the UI but still the UI is not updating. It is not drawing the path. Can you please find the mistake because the code is working sometimes with breakpoints but sometimes it is not working.
- (IBAction)navigateActbtn:(id)sender {
NSString *str = [NSString stringWithFormat:#"%#origin=%f,%f&destination=%f,%f&key=%#",#"https://maps.googleapis.com/maps/api/directions/json?",
self.marker.position.latitude,
self.marker.position.longitude,
self.SecondMarker.position.latitude,
self.SecondMarker.position.longitude,
#"USEURAPIKEY"];
str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:str];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:request
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
self.dataReceive = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
// handle response
if (!error && [data length]) {
dispatch_sync(dispatch_get_main_queue(), ^{
[self mainQueue];
});
}
else{
NSLog(#"%#",error.description);
}
}] resume];
}
-(void)mainQueue{
NSLog(#"main queue");
self.path1 =[GMSPath pathFromEncodedPath:self.dataReceive[#"routes"][0][#"overview_polyline"][#"points"]];
_singleLine = [GMSPolyline polylineWithPath:self.path1];
_singleLine.strokeWidth = 7;
_singleLine.strokeColor = [UIColor greenColor];
_singleLine.map = self.mapView;
}

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 Design the Overlay Menu Above the Home Page?

How to Design the Overlay Instructions Above The View?
I HAD 6 buttons....For Each Button I have To show Overlay For That, Before i click on that Button
Suppose... 1) Click button is there...above the Click Button we need
to show overlay for click on that button Like That...
**
[I Need Like This Overlay menu over the all Buttons][1]
[1]: http://i.stack.imgur.com/dIjRF.jpg
**
Use NSURLSession instead. NSURLConnection is deprecated.
NSString *stringURL = [NSString stringWithFormat:#"%#?term=%#", BASE_URL, _inputText.text];
NSURL *URL = [NSURL URLWithString:stringURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"POST"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:yourData completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// Do your stuff here
}];
why not use alamofire---
NSDictionary *parameters = #{
#"email": #"myemail1#mailinator.com",
#"password": #"123456789",
#"accountnumber": #"LiM6N5gBBmqdlQBJGkqcP0h4OKwGbnzoWFcgTG3Z",
#"ifcscode": #"ABC"
};
NetworkHandler *networHandler = [NetworkHandler sharedInstance];
[networHandler composeRequestWithMethod:#"http://example.com/enpoint.json"
paramas: parameters
onComplition:^(BOOL success, NSDictionary *response){
if (success) { //handle success response
[self handleLoginResponse:response];
}
else{
ProgressIndicator *pi = [ProgressIndicator sharedInstance];
[pi hideProgressIndicator];
}
}];
you can use postman to check your api
Pass this two variables of FirstViewController to SecondViewController and then try to put below code in place of your code.
Below is code to POST data using NSURLSession.
I hope this works for you.
-(void)postData
{
NSString *content = [NSString stringWithFormat:#"Name=%#&Email=%#&A/CName=%#&A/CNumber=%#&IFSCCode=%#&TypeOfAccount=%#",name,email,acName,acNumber,ifscCode,typeOfAccount];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:#"your web service url"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[content dataUsingEncoding:NSUTF8StringEncoding]];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
NSMutableDictionary *dictJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Dict Json :- %#",dictJson);
}] resume];
}
Send Parameter to web service using POST method
Below is code to POST data to web service using NSURLConnection.
-(void)postData
{
NSString *content = [NSString stringWithFormat:#"email=%#&name=%#",textEmail.text,textName.text];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:#"your web service url"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[content dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
dictJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Dict Json :- %#",dictJson);
}

Objective-C issues with dataTaskWithRequest

I have recently switched from sendSynchronousRequest to dataTaskWithRequest
with sendSynchronousRequest my method was working perfectly but when I switch to dataTaskWithRequest I get the following error:
error NSURLError * domain: #"NSURLErrorDomain" - code: 4294966096 0x15ee96c0
and
myError NSError * domain: nil - code: 1684370017 0x26cce125
I don't understand why.
Here is the old code (commented out) and the new code:
/*-(NSDictionary *)GetProductionScheduleData:(NSString *)areaDescription
{
NSString *areaDescriptionWSpaceCharacters = [areaDescription stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *requestString = [NSString stringWithFormat:#"%#?areaDescription=%#",kIP,areaDescriptionWSpaceCharacters];
NSURL *JSONURL = [NSURL URLWithString:requestString];
NSURLResponse* response = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
if(data == nil)
return nil;
NSError *myError;
NSDictionary *productionSchedule = [[NSDictionary alloc]initWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
return productionSchedule;
}*/
-(void)GetProductionScheduleData:(NSString *)areaDescription Completetion:(void (^) (NSMutableDictionary * result,NSError * error))completion{
NSString *areaDescriptionWSpaceCharacters = [areaDescription stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *requestString = [NSString stringWithFormat:#"%#?areaDescription=%#",kIP,areaDescriptionWSpaceCharacters];
NSURL *JSONURL = [NSURL URLWithString:requestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSError *myError;
NSMutableDictionary *productionSchedule = [[NSMutableDictionary alloc]initWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
completion(productionSchedule,myError);
}];
[dataTask resume];
}
Please Help! This was working with sendSynchronousRequest I am starting to dislike dataTaskWithRequest.
The NSURLSession code you have is correct, I confirmed with a valid URL.
You stopped checking to see if data is nil before attempting to JSON parse it. If you add that check back I bet you'll find that there is an error and data is in fact nil.
Change to:
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
// handle request error
if (error) {
completion(nil, error);
return;
}
NSError *myError;
NSMutableDictionary *productionSchedule = [[NSMutableDictionary alloc]initWithDictionary:[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&myError]];
completion(productionSchedule,myError);
}];
I would recommend also checking myError before attempting to set it to productionSchedule (which could also cause a crash).

Resources