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

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);
}
}
}];
}

Related

Pause/Resume download with AFNetworking 3.0 and NSURLSessionDownloadTask Objective-C, OSX

I have trouble with creating Pause/Resume download methods in my Objective-C osx app, I have tried some of the answers I found here but nothing seems to work.
Here is my code: `-(void)pauseDownload:(id)sender {
if(!downloadTask) return;
[downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
if (!resumeData) return;
[self setDownloadResumeData:resumeData];
[self setDownloadTask:nil];
}];
NSString *datastring = [[NSString alloc] initWithData:downloadResumeData encoding:NSUTF8StringEncoding];
isDownloading = NO;
NSLog(#"data %#", datastring);}`
Continue method:
-(void)continueDownload:(id)sender {
if (!self.downloadResumeData) {
return;
}
self.downloadTask = [manager.session downloadTaskWithResumeData:self.downloadResumeData];
[self.downloadTask resume];
[self setDownloadResumeData:nil];}
And download request with download task:
-(void)downloadRequest:(NSString *)url toDirectory:(NSString *)directoryName atIndex:(NSInteger) rowIndex {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSString *downloadDirectoryPath = [[NSUserDefaults standardUserDefaults] objectForKey:#"downloadPath"];
NSURL *downloadURL;
if (directoryName != nil || ![directoryName isEqualToString:#""]) {
downloadURL = [self createDownloadDirectoryIn:downloadDirectoryPath withName:directoryName];
} else {
downloadURL = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:#"downloadFolderPath"]];
}
downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
NSLog(#"%#", downloadProgress);
// [self downloadStartedWithDownloadId:downloadID andDeviceId:userDeviceID];
isDownloading = YES;
NSNumber *downloadPercentage = [NSNumber numberWithInteger:downloadProgress.fractionCompleted *100];
progressArray[rowIndex] = downloadPercentage;
[self updateProgressBars];
} destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
return [downloadURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
[[files objectAtIndex:self.tableOfContents.selectedRow] setIsFinishedDownloading:YES];
// [self downloadFinishedWithDownloadID:downloadID andDeviceID:userDeviceID];
NSLog(#"File downloaded to: %#", filePath);
}] ;
[downloadTask resume];}
Appreciate any help.

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 to change my synchronous to asynchronous call in Objective-C?

hi friend i am beginner for objective-c.i have slow response from server side due to synchronous call. i analysed in google the call may be asynchronous means the response speed will be high, but i don't know much about NSURLConnection and GCD. so please help me how to change my call asynchronous . see my code below`
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString* oldToken = [self deviceToken];
NSString *newToken = [[[[deviceToken description]stringByReplacingOccurrencesOfString:#"<"withString:#""]
stringByReplacingOccurrencesOfString:#">" withString:#""]
stringByReplacingOccurrencesOfString: #" " withString: #""];
NSLog(#"My token is: %#", newToken);
[self setDeviceToken:newToken];
if (![newToken isEqualToString:oldToken])
{
[self calur:newToken];
}
}
- (NSString*)deviceToken{
return [[NSUserDefaults standardUserDefaults] stringForKey:#"deviceid"];
}
- (void)setDeviceToken:(NSString*)token{
[[NSUserDefaults standardUserDefaults] setObject:token forKey:#"deviceid"];
}
//This function used to store a notification device id to our notification databae
-(void)calur:(NSString *)device
{
NSString *post =[NSString stringWithFormat:#"deviceId=%#",device];
NSString *hostStr = #"https://myserver.com/Ver_2_0/notification/check.php?";
NSError *error = nil;
NSString *nocon=[NSString stringWithContentsOfURL:[NSURL URLWithString:hostStr]encoding:NSUTF8StringEncoding error:&error];
if (nocon == nil)
{
NSLog(#"NO Connection");
}
else
{
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"hostStr=%#",hostStr);
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"dataURL=%#",dataURL);
// NSData *dataurl=dataURL;
if([serverOutput isEqualToString:#"Token Updated Successfully"])
{
NSLog(#"badge updated");
}
else
{
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"not registered");
}
[serverOutput release];
}
}`
if (nocon == nil)
{
NSLog(#"NO Connection");
}
else
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
hostStr = [hostStr stringByAppendingString:post];
NSData *dataURL = [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];
NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
NSLog(#"hostStr=%#",hostStr);
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"dataURL=%#",dataURL);
// NSData *dataurl=dataURL;
if([serverOutput isEqualToString:#"Token Updated Successfully"])
{
NSLog(#"badge updated");
}
else
{
NSLog(#"serverOutput = %#",serverOutput);
NSLog(#"not registered");
}
[serverOutput release];
});
}
a little snippet:
#import "AFNetworking.h"
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:self.value, #"POSTvar", nil];
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL: [NSURL URLWithString:#"http://your.address"]];
NSURLRequest *request = [client requestWithMethod:#"POST" path:nil parameters:params];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// do some with JSON
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
});
AFNetworking github

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.
}];