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

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

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 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"];

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.

Fetch only MyContacts from gmail account in iOS

I am trying to fetch gmail & yahoo contacts in my iPhone application.
For Gmail I have used GTMOauth2.0. I can see all contacts but when I want only contacts from MyContacts group. I have used following code to get contacts:
-(void)signInToGoogle:(id)sender
{
[self signOutFromGoogle];
NSString *keychainItemName = nil;
NSString *scope = #"https://www.google.com/m8/feeds/contacts/default/full";
NSString *clientID = #"CLIENTID";
NSString *clientSecret = #"CLIENTSECRETID";
SEL finishedSel = #selector(viewController:finishedWithAuth:error:);
GTMOAuth2ViewControllerTouch *viewController;
viewController = [GTMOAuth2ViewControllerTouch controllerWithScope:scope
clientID:clientID
clientSecret:clientSecret
keychainItemName:keychainItemName
delegate:self
finishedSelector:finishedSel];
NSDictionary *params = [NSDictionary dictionaryWithObject:#"en" forKey:#"hl"];
viewController.signIn.additionalAuthorizationParameters = params;
NSString *html = #"<html><body bgcolor=silver><div align=center>Loading sign-in page...</div></body></html>";
viewController.initialHTMLString = html;
[[self navigationController] pushViewController:viewController animated:YES];
}
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error {
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (error != nil) {
[processObj removeFromSuperview];
self.view.userInteractionEnabled = YES;
NSLog(#"Authentication error: %#", error);
NSData *responseData = [[error userInfo] objectForKey:#"data"]; // kGTMHTTPFetcherStatusDataKey
if ([responseData length] > 0) {
// show the body of the server's authentication failure response
NSString *str = [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding];
NSLog(#"%#", str);
}
self.auth = nil;
} else {
self.auth = auth;
[self doAnAuthenticatedAPIFetch];
}
}
- (void)doAnAuthenticatedAPIFetch {
NSString *urlStr = #"https://www.google.com/m8/feeds/groups/default/full/Contacts";
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];
}
}
}];
}
In the API I am passing "Contacts" as a group id but it is returning error "Group Id Not Found". I have the google document from
https://developers.google.com/google-apps/contacts/v3/?csw=1
but still can't solve the problem. Help me on these.
You'll need to fetch the groups feed to get the ID for a group. See the groups feed documentation, or try the ContactsSample app provided with the Google Data APIs Objective-C Client Library.

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.