CouchDb views not updating - objective-c

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.

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.

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 server error message while parsing json using NSURLConnection in 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"];

How to fetch gmail Contacts in iOS application using google contacts api?

In my application we kept option to login through gmail. I have requirement to retrieve gmail contacts.
In the following method i am using auth object(once success) to fetch gmail contacts by creating request with url: "https://www.google.com/m8/feeds/contacts/default/full"
- (void)finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error {
if(!error) {
auth.clientID =myClientId;
auth.clientSecret =myClientSecret;
auth.scope= #"https://www.googleapis.com/auth/contacts.readonly";
NSString *urlStr = #"https://www.google.com/m8/feeds/contacts/default/full";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"GET"];
[request setValue:#"3.0" forHTTPHeaderField:#"GData-Version"];
[auth authorizeRequest:request
completionHandler:^(NSError *error) {
NSString *output = nil;
if (error) {
output = [error description];
} else {
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (data) {
// API fetch succeeded :Here I am getti
output = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
NSLog(#"%#",output);
} else {
// fetch failed
output = [error description];
}
}
}];
}
}
I'm getting client error(401). is there any thing i'm missing to my request.
The correct Scope is "https://www.google.com/m8/feeds"
In swift
class func getContactsFromUser() {
let urlStr = "https://www.google.com/m8/feeds/contacts/default/full"
let url = NSURL(string: urlStr);
var request = NSMutableURLRequest(URL: url!)
let appd = UIApplication.sharedApplication().delegate as! AppDelegate
let error: NSError!
appd.service.authorizer.authorizeRequest!(request, completionHandler: { (error) -> Void in
if error != nil {
println("error getting contacts is \(error.localizedDescription)")
} else {
let response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil
let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: response, error: nil)
if data != nil {
let stringResponse = NSString(data: data!, encoding: NSUTF8StringEncoding)
println("**** stringResponse **** \(stringResponse!)")
} else {
println("error 2 getting contacts is ")
}
}
})
}
In objective c
- (void)doAnAuthenticatedAPIFetch {
NSString *urlStr = #"https://www.google.com/m8/feeds/contacts/default/full";
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[self.auth authorizeRequest:request
completionHandler:^(NSError *error) {
NSString *output = nil;
if (error) {
output = [error description];
} else {
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
if (data) {
// API fetch succeeded :Here I am getti
output = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];
} else {
// fetch failed
output = [error description];
}
}
}];
}

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