Getting server error message while parsing json using NSURLConnection in Objective C - objective-c

[
{
"CouponQtn":1,
"DeliveryDist":14,
"Sizes":"not selected",
"CustomerAlternateMobile":"01700790900",
"deliveryCharge":0,
"DealId":744706,
"PaymentType":"MPD",
"OrderFrom":"ios",
"CardType":"Manual",
"OrderSource":"app",
"CustomerId":630142,
"MerchantId":15196,
"AdvPaymentType":0,
"CustomerBillingAddress":"Khulna",
"CustomerMobile":"01700790900",
"Color":"",
"AdvPayPhoneId":0,
"OrderCouponPrice":375
}
]
This is my json format populated from the app and I am sending it to server in a post method to get a desired json result. But the server is providing me an unknown error. But it is working in Postman as well
Here I convert my array of dictionary to json
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:orderArray
options:kNilOptions
error:nil];
NSString*jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//NSString* jsonStr = [NSString stringWithUTF8String:[jsonData bytes]];
tempDic = [apiCom getNodeDataByPOST:CART_ORDER_URL parameter:[NSString stringWithFormat:#"%#",jsonStr]];
Here orderArray is my array of dictionary and my parsing code is provided below
-(NSDictionary*)getNodeDataByPOST:(NSString*)url parameter:(id)parameter{
NSDictionary *dictionaryData;
NSDictionary *dic;
Reachability *reachTest = [Reachability reachabilityWithHostName:#"www.apple.com"];
NetworkStatus internetStatus = [reachTest currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)){
dictionaryData = [[NSDictionary alloc] initWithObjectsAndKeys:#"error",#"status",#"No Network",#"message",nil];
dic = [NSDictionary dictionaryWithObjectsAndKeys:dictionaryData, #"response",nil];
return dic;
}
else{
NSURL *adUrl =[NSURL URLWithString:url];
NSMutableURLRequest *requestURL = [NSMutableURLRequest requestWithURL:adUrl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:900.00];
//NSLog(#"%#",requestURL);
[requestURL setHTTPMethod:#"POST"];
NSError *error=nil ;
if ([parameter isKindOfClass : [NSString class]]) {
[requestURL setHTTPBody:[parameter dataUsingEncoding:NSUTF8StringEncoding]];
}
// else if([parameter isKindOfClass:[NSDictionary class]]) {
// [requestURL setHTTPBody:parameter];
// }
else if([parameter isKindOfClass:[NSArray class]]||[parameter isKindOfClass:[NSDictionary class]]) {
[requestURL setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameter options:0 error:nil]];
}
else {
[requestURL setHTTPBody:parameter];
}
NSHTTPURLResponse *response;
NSError *error1=nil;
// NSLog(#"%#\n\n%#",s,parameter);
NSData *apiData = [NSURLConnection sendSynchronousRequest:requestURL returningResponse:&response error:&error1];
if (!apiData) {
NSLog(#"Error: %#", [error localizedDescription]);
}
if (response.statusCode == 0) {
dictionaryData = [[NSDictionary alloc] initWithObjectsAndKeys:#"error",#"status",#"Server Error",#"message",nil];
return dic;
}
else if(response.statusCode == 404) {
dictionaryData= [[NSDictionary alloc] initWithObjectsAndKeys:#"error",#"status",#"Server is Currently Down.",#"message", nil];
return dic;
}
else {
dictionaryData = [NSJSONSerialization JSONObjectWithData:apiData options:kNilOptions error:&error];
}
}
return dictionaryData;
}
I didn't find any coding or logical error from my side. I have used this code several times and it worked fine. Is there any settings are permission required in the app side?
Thanks ....

You said that its working fine in Postman, you should check if the request in to send in form-url encoded formate. If it is, you should add the following line
[requestURL setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];

I use this line and works like a magic for me
[requestURL setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];

Related

The operation couldn't be completed (nsurlErrorDomain error -1012)

I have checked and applied it's all possible answers but not getting any success because I couldn't find the reason.
I am calling an API and sometimes it is working fine but some time it is giving me "The operation couldn't be completed (nsurlErrorDomain error -1012)" error.
My API calling code:
I have created this global method to call APIs. For this, I have created a singleton class.
-(void)getDispatchDetail:(NSString *)strDispatchId successBlock:(void(^)(NSDictionary *response))successBlock withFailureBlock:(FailureBlock)failureBlock{
NSString *urlString = [NSString stringWithFormat:#"%#%#",BASE_URL,END__POINT_getDispatchDetail];
[self MethodType:POST URL:urlString parameters:#{#"DispatchId":strDispatchId?strDispatchId:#""} withCookies:nil completionBlockWithSuccess:^(id responseObject, NSURLResponse *urlResponse) {
successBlock(responseObject);
} failure:^(NSError *error) {
[ProgressHUD dismiss];
failureBlock(error);
}];
}
-(void)MethodType:(METHOD_TYPE)methodType
URL:(NSString *)urlString
parameters:(NSDictionary *)param
withCookies:(BOOL)isCookies completionBlockWithSuccess:(void (^)(id responseObject, NSURLResponse *urlResponse))success
failure:(void (^)(NSError *error))failureRequest
{
if (isCookies){
//[ProgressHUD show:kSTRING_LOADING Interaction:NO];
}
/**
Create URl based on the Request Type
**/
NSURL *url;
switch (methodType) {
case GET:
if (param) {
NSString *strDict = [self stringFromDictionary:param];
NSString *strURL = [NSString stringWithFormat:#"%#?%#",urlString,strDict];
strURL = [strURL stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
url = [NSURL URLWithString:strURL];
break;
}
url = [NSURL URLWithString:urlString];
break;
case PUT:
case POST:
case DELETE:
url = [NSURL URLWithString:urlString];
break;
default:
break;
}
/**
Create Reuqest based on the Request Type
**/
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
switch (methodType) {
case GET:
[req setHTTPMethod:#"GET"];
break;
case POST:
{
[req setHTTPMethod:#"POST"];
NSError *error = nil;
NSData *postData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:&error];
if (error) {
failureRequest(error);
}
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[req setHTTPBody:postData];
}
break;
case PUT:
{
[req setHTTPMethod:#"PUT"];
NSError *error = nil;
if (param != nil) {
NSData *postData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:&error];
[req setHTTPBody:postData];
}
if (error) {
failureRequest(error);
}
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
}
break;
case DELETE:
{
[req setHTTPMethod:#"DELETE"];
}
break;
default:
break;
}
//self.strAccessToken = #"Token ab6520a0805b11e82c750034548b74d02464e900";
//self.strAccessToken = [ETDataModelClass getUserAccessToken];
if ([[NSUserDefaults standardUserDefaults] valueForKey:API_PARAM_USER_ACCESS_TOKEN] != nil) {
NSDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:kUserLoginTokenAndData];
NSString *tokenType = [dict objectForKey:#"token_type"];
self.strAccessToken = [NSString stringWithFormat:#"%# %#",tokenType,[[NSUserDefaults standardUserDefaults] valueForKey:API_PARAM_USER_ACCESS_TOKEN]];
// [self.strAccessToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[req setValue:self.strAccessToken forHTTPHeaderField:API_ACCESS_TOKEN];
}
NSLog(#"ReqType : %# URL : %#, Param : %#", [self getMethodTypeName:methodType], url, param);
NSLog(#"User Token : %#",_strAccessToken);
[req setTimeoutInterval:60.0];
[NSURLConnection sendAsynchronousRequest:req
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *responseHeader, NSData *responseBody, NSError *error)
{
NSError *errorData = nil;
NSLog(#"Response Header : %#", responseHeader);
NSLog(#"Response : %#", [[NSString alloc] initWithData:responseBody encoding:NSUTF8StringEncoding]);
id responseObject1;
if(![responseBody isKindOfClass:[NSNull class]] && responseBody != nil)
responseObject1 = [NSJSONSerialization JSONObjectWithData:responseBody options:NSJSONReadingMutableLeaves error:&errorData];
else{
[ProgressHUD dismiss];
[Utility showAlertMessage:#"No Internet Connection. Make sure your device is connected to the internet." WithTitle:#""];
return ; // When response body nil we will return the control
}
// NSLog(#"Server Response ===> :\n %#", responseObject1);
// NSLog(#"Server Error ===> :\n %#", errorData);
if (error) {
if([responseObject1 isKindOfClass:[NSDictionary class]]){
if([[responseObject1 objectForKey:API_Alert_MESSAGE] isEqualToString:kAutologoutResponseFromServer]){
NSLog(#" Response ===== %# =====", responseObject1);
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationAutoLogout object:nil userInfo:responseObject1];
}
}
[ProgressHUD dismiss];
failureRequest(error);
return ;
}
else {
//[ProgressHUD dismiss];
if (!errorData) {
if (responseObject1 == nil) {
return [Utility showAlertMessage:NO_DATA_AVAILABLE WithTitle:#""];
}
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) responseHeader;
long statusCode = httpResponse.statusCode;
NSLog(#"statusCode : %ld",statusCode);
switch (statusCode) {
case API_STATUS_CODE_200: case API_STATUS_CODE_402:
if (success) {
success(responseObject1,responseHeader);
}
break;
case API_STATUS_CODE_500: case API_STATUS_CODE_400:
NSLog(#"responseHeader : %#",responseHeader);
NSLog(#"responseBody : %#",[[NSString alloc] initWithData:responseBody encoding:NSUTF8StringEncoding]);
NSLog(#"error : %#",error.localizedDescription);
NSLog(#"%#",[[NSString alloc] initWithData:responseBody encoding:NSUTF8StringEncoding]);
[Utility showAlertMessage:SERVER_ERROR WithTitle:#""];
[ProgressHUD dismiss];
break;
case API_STATUS_CODE_403:{
NSLog(#"auto logout warning : %#",responseBody);
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationAutoLogout object:nil userInfo:responseObject1];
[ProgressHUD dismiss];
break;
}
default:
NSLog(#"responseHeader : %#",responseHeader);
NSLog(#"responseBody : %#",[[NSString alloc] initWithData:responseBody encoding:NSUTF8StringEncoding]);
NSLog(#"error : %#",error.localizedDescription);
NSLog(#"%#",[[NSString alloc] initWithData:responseBody encoding:NSUTF8StringEncoding]);
if([responseObject1 isKindOfClass:[NSDictionary class]])
if([responseObject1 valueForKey:API_Alert_MESSAGE] && [responseObject1 valueForKey:API_Alert_MESSAGE] != nil)
[Utility showAlertMessage:[responseObject1 valueForKey:API_Alert_MESSAGE] WithTitle:#""];
[ProgressHUD dismiss];
break;
}
}
else{
failureRequest(errorData);
}
}
}];
}

Getting error while fetching data from server using NSURLSession Datatask in objective c

I was trying to load data for the table using values from server.I am using NSURLSession datatask with completion handler. Whenever it reaches the nsurlsession, it shows error.This is the code which i used for getting data.
- (void)geturl:(NSString *)urlvalue datavalues:(NSString *)string fetchGreetingcompletion:(void (^)(NSDictionary *dictionary, NSError *error))completion{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#?%#",common.getUrlPort,urlvalue,common.getappversion]];
NSLog(#"url=%#",url);
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest addValue:common.getauthtoken forHTTPHeaderField:#"Authorization"];
//Create POST Params and add it to HTTPBody
[urlRequest setHTTPMethod:#"GET"];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *connectionError) {
NSLog(#"Response:%# %#\n", response, connectionError);
if (data.length > 0 && connectionError == nil)
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSString *code = [NSString stringWithFormat:#"%#",[greeting valueForKey:#"code"]];
if([code isEqualToString:#"-1"]){
[self loaderrorview:greeting];
}
else{
if (completion)
completion(greeting, connectionError);
}
}
else if(data == nil){
NSDictionary *errorDict=[[NSDictionary alloc]initWithObjectsAndKeys:#"Server Connection Failed",#"error", nil];
if (completion)
completion(errorDict,connectionError);
}
else
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
if (completion)
completion(greeting, connectionError);
}
}];
[dataTask resume];
}
The code which i used for getting data from server:
-(void)getdataexplore{
if (!common.checkIfInternetIsAvailable) {
[self.view makeToast:Nointernetconnection];
} else {
NSLog(#"There is internet connection");
[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
[SVProgressHUD showWithStatus:#"Loading..."];
[apiservice geturl:loadexploredata datavalues:nil fetchGreetingcompletion:^(NSDictionary *dictionary, NSError *error) {
//NSLog(#"Test %# Error %#",dictionary,error);
if(error == nil){
authDictionary = dictionary;
[self loaddata];
}
else{
[SVProgressHUD dismiss];
[view_business makeToast:#"Request timed out" duration:2.0 position:CSToastPositionCenter];
}
}];
}
}
The code which i used for storing server data to array:
-(void)loaddata
{
[SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
[SVProgressHUD showWithStatus:#"Loading..."];
//[SVProgressHUD dismiss];
NSString *msg = [authDictionary valueForKey:#"msg"];
NSString *code = [NSString stringWithFormat:#"%#",[authDictionary valueForKey:#"code"]];
if([code isEqualToString:#"201"]){
NSDictionary *explore = [authDictionary valueForKey:#"explore_obj"];
arr_CBcategories = [explore valueForKey:#"cb_categories"];
[common setarrCBCaterory:arr_CBcategories];
arr_CBcategoryid = [arr_CBcategories valueForKey:#"id"];
[common setarrCateroryID:arr_CBcategoryid];
arr_CBcategorytitle = [arr_CBcategories valueForKey:#"title"];
[common setarrCaterorytitle:arr_CBcategorytitle];
arr_CBcategoryslug = [arr_CBcategories valueForKey:#"slug"];
[common setarrCateroryslug:arr_CBcategoryslug];
arr_CBcategoryimage = [arr_CBcategories valueForKey:#"image"];
[common setarrCateroryimage:arr_CBcategoryimage];
arr_CBcategorycode = [arr_CBcategories valueForKey:#"code"];
}
I am getting error like "Unable to run main thread". Any solution for this.

CouchDb views not updating

Okay I'm currently using CouchDb v 1.2.0 for a scheme application with objective-c. When i run my program I'm deleting the old version of the database and creating a new one like this:
CouchDb *couchDb = [[CouchDb alloc]init];
//Deleting the old version of the db if it exists for xcode demo
[couchDb deleteDb:#"timevault" onComplete:^(NSString *message) {
NSLog(#"%#", message);
}];
//Creating a new db
[couchDb createDb:#"timevault" onComplete:^(NSString *message) {
NSLog(#"%#", message);
}];
//Creating views to get students and courses
NSString *viewCourses = #"function (doc) { if (doc.type === \"Course\") { emit(doc._id, doc); } }";
NSString *viewStudents = #"function (doc) { if (doc.type === \"Student\") { emit(doc._id, doc); } }";
NSDictionary *views = #{#"views": #{#"courses": #{#"map":viewCourses}, #"students": #{#"map":viewStudents}}};
//Saving design document to db
[couchDb createViewInDb:views onComplete:^(NSString *message) {
NSLog(#"%#", message);
}];
Class implementation:
-(void)deleteDb:(NSString *)name onComplete:(message)message{
NSMutableString *url = [[NSMutableString alloc]initWithString:#"http://localhost:5984/"];
[url appendString:name];
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"DELETE"];
NSURLResponse *responseCode = nil;
NSError *error = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
if (!error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)responseCode;
NSNumber *responseStatusCode = [[NSNumber alloc] initWithLong:[httpResponse statusCode]];
if ([responseStatusCode isEqualToNumber:[NSNumber numberWithInt:200]]) {
message([NSString stringWithFormat:#"Old db %# deleted", name]);
}
}else {
message([NSString stringWithFormat:#"Error: %#", [error localizedDescription]]);
}
}
-(void)createDb:(NSString *)name onComplete:(message)message{
NSMutableString *url = [[NSMutableString alloc]initWithString:#"http://localhost:5984/"];
[url appendString:name];
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"PUT"];
NSURLResponse *responseCode = nil;
NSError *error = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
if (!error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)responseCode;
NSNumber *responseStatusCode = [[NSNumber alloc] initWithLong:[httpResponse statusCode]];
if ([responseStatusCode isEqualToNumber:[NSNumber numberWithInt:412]]) {
message(#"Db already exists, no new Db was created");
}else if ([responseStatusCode isEqualToNumber:[NSNumber numberWithInt:201]]){
message([NSString stringWithFormat:#"Db %# created", name]);
}
}else {
message([NSString stringWithFormat:#"Error: %#", [error localizedDescription]]);
}
}
-(void)createViewInDb:(NSDictionary *)view onComplete:(message)message{
NSMutableString *url = [[NSMutableString alloc]initWithString:URL];
[url appendString:#"/_design/app"];
request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"PUT"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-type"];
NSData *asJson = [NSJSONSerialization dataWithJSONObject:view options:NSUTF8StringEncoding error:nil];
[request setHTTPBody:asJson];
NSURLResponse *responseCode = nil;
NSError *error = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];
if (!error){
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)responseCode;
NSNumber *responseStatusCode = [[NSNumber alloc] initWithLong:[httpResponse statusCode]];
if ([responseStatusCode isEqualToNumber:[NSNumber numberWithInt:201]]) {
message(#"Views in Db created");
}
}else {
message([NSString stringWithFormat:#"Error: %#", [error localizedDescription]]);
}
}
All of this is with synchronous requests. For the couchdb pros out there that doesn't know obj-c, I'm basically saying this:
DELETE http://localhost:5984/database/
PUT http://localhost:5984/database/
PUT http://localhost:5984/database/_design/app,
content-type: application/json
with body:
{"views":
{
"courses": {
"map": "function (doc) {
if (doc.type === \"Course\") {
emit(doc._id, doc);
}}"
},
"students": {
"map": "function (doc) {
if (doc.type === \"Student\") {
emit(doc._id, doc);
}}"
}}
}
My problem here is that my view: http://localhost:5984/database/_design/app/_view/students only works like half of the time, the other half it's not updating, I'm getting old id's, why is this?
I'm not looking at the old version of the db because I'm creating new documents of students and courses and that's working. Am I missing something when I'm deleting the db that concerns the _design document? I googled around on this but can't find anything that solves my problem.

How do I loop through tweets to access geo information and add to an array

How would I loop through the JSON returned by a TWRequest to get the geo information of a tweet? I am using the code below - I have marked up the bit I am unsure about. the text component works fine, I'm just not sure how to create the array of geo data and access this...
- (void)fetchTweets
{
AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
//NSLog(#"phrase carried over is %#", delegate.a);
// Do a simple search, using the Twitter API
TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:
[NSString stringWithFormat:#"http://search.twitter.com/search.json?q=%#", delegate.a]]
parameters:nil requestMethod:TWRequestMethodGET];
// Notice this is a block, it is the handler to process the response
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if ([urlResponse statusCode] == 200)
{
// The response from Twitter is in JSON format
// Move the response into a dictionary and print
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
//NSLog(#"Twitter response: %#", dict);
NSArray *results = [dict objectForKey:#"results"];
//Loop through the results
for (NSDictionary *tweet in results) {
// Get the tweet
NSString *twittext = [tweet objectForKey:#"text"];
//added this one - need to check id NSString is ok??
NSString *twitlocation = [tweet objectForKey:#"geo"];
// Save the tweet to the twitterText array
[_twitterText addObject:twittext];
//this is the loop for the location
[twitterLocation addObject:twitlocation];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
else
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
}
"geo" is deprecated and probably not filled at all. I far as I remember it was deprecated in Twitter API v1.0 too. Try this code:
- (void)fetchTweets
{
AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
//NSLog(#"phrase carried over is %#", delegate.a);
// Do a simple search, using the Twitter API
TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:
[NSString stringWithFormat:#"http://search.twitter.com/search.json?q=%#", delegate.a]]
parameters:nil requestMethod:TWRequestMethodGET];
// Notice this is a block, it is the handler to process the response
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if ([urlResponse statusCode] == 200)
{
// The response from Twitter is in JSON format
// Move the response into a dictionary and print
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
//NSLog(#"Twitter response: %#", dict);
NSArray *results = [dict objectForKey:#"results"];
//Loop through the results
for (NSDictionary *tweet in results) {
// Get the tweet
NSString *twittext = [tweet objectForKey:#"text"];
//added this one - need to check id NSString is ok??
id jsonResult = [tweet valueForKeyPath:#"coordinates.coordinates"];
if ([NSNull null] != jsonResult) {
if (2 == [jsonResult count]) {
NSDecimalNumber* longitude = [jsonResult objectAtIndex:0];
NSDecimalNumber* latitude = [jsonResult objectAtIndex:1];
if (longitude && latitude) {
// here you have your coordinates do whatever you like
[twitterLocation addObject:[NSString stringWithFormat:#"%#,%#", latitude, longitude]];
}
else {
NSLog(#"Warning: bad coordinates: %#", jsonResult);
}
}
else {
NSLog(#"Warning: bad coordinates: %#", jsonResult);
}
}
// Save the tweet to the twitterText array
[_twitterText addObject:twittext];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
else
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
}

Returning NSDictionary from async code block? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
returning UIImage from block
Hi I'm trying to return dictionary of json twitter data so i can use it in my application. How ever it is being called from a async block. I can not save it or return it any thoughts?
-(NSDictionary *)TweetFetcher
{
TWRequest *request = [[TWRequest alloc] initWithURL:
[NSURL URLWithString: #"http://search.twitter.com/search.json?
q=iOS%205&rpp=5&with_twitter_user_id=true&result_type=recent"] parameters:nil
requestMethod:TWRequestMethodGET];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse
*urlResponse,
NSError *error)
{
if ([urlResponse statusCode] == 200)
{
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData
options:0 error:&error];
//resultsArray return an array [of dicitionaries<tweets>];
NSArray* resultsArray = [dict objectForKey:#"results"];
for (NSDictionary* internalDict in resultsArray)
NSLog([NSString stringWithFormat:#"%#", [internalDict
objectForKey:#"from_user_name"]]);
----> return dict; // i need this dictionary of json twitter data
}
else
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
}
Thnx in advance!
I feel like I've written a ton of this async code lately.
- (void)tweetFetcherWithCompletion:(void(^)(NSDictionary *dict, NSError *error))completion
{
NSURL *URL = [NSURL URLWithString:#"http://search.twitter.com/search.json?q=iOS%205&rpp=5&with_twitter_user_id=true&result_type=recent"];
TWRequest *request = [[TWRequest alloc] initWithURL:URL parameters:nil requestMethod:TWRequestMethodGET];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if ([urlResponse statusCode] == 200) {
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
if (error) {
completion(nil, error);
return;
}
//resultsArray return an array [of dicitionaries<tweets>];
NSArray* resultsArray = [dict objectForKey:#"results"];
for (NSDictionary* internalDict in resultsArray)
NSLog(#"%#", [internalDict objectForKey:#"from_user_name"]);
completion(dict, nil);
}
else {
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
completion(nil, error);
}
}];
}
So, instead of calling self.tweetDict = [self TweetFetcher];, you would call it this way.
[self tweetFetcherWithCompletion:^(NSDictionary *dict, NSError *error) {
if (error) {
// Handle Error Somehow
}
self.tweetDict = dict;
// Everything else you need to do with the dictionary.
}];