I just built my first app and there is only one thing left to do. I am getting data from a url. If that URL fails or is nil then I would like to get the data from the User Defaults.
I have a function that saves the user defaults from the data off the URL
- (void)saveToUserDefaults
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:data forKey:#"data"];
[defaults synchronize];
}
and here is some more of my code.
NSURL *url = [NSURL URLWithString:#"http://jamessuske.com/isthedomeopen/isthedomeopenGetData.php"];
data = [NSData dataWithContentsOfURL:url options:0 error:nil];
[self saveToUserDefaults];
if(url == nil){
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
data = [defaults dataForKey:#"data"];
}
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
I disconnected from the internet and ran my app in a simulator and my app returned empty values.
What can I do to fix this?
Try this for your scenario
// method used to check network is available or not
- (BOOL)isNetworkAvailable
{
BOOL connected;
const char *host = "www.apple.com";
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host);
SCNetworkReachabilityFlags flags;
connected = SCNetworkReachabilityGetFlags(reachability, &flags);
isConnected = NO;
isConnected = connected && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
CFRelease(reachability);
return isConnected;
}
}
now try to check
NSURL *url = [NSURL URLWithString:#"http://jamessuske.com/isthedomeopen/isthedomeopenGetData.php"];
data = [NSData dataWithContentsOfURL:url options:0 error:nil];
bool networkStatus = [self isNetworkAvailable];
if(networkStatus){
[self saveToUserDefaults];
}
else
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
data = [defaults objectForKey:#"data"];
}
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
try this
- (void)saveToUserDefaults
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:data forKey:#"data"];
}
NSURL *url = [NSURL URLWithString:#"http://jamessuske.com/isthedomeopen/isthedomeopenGetData.php"];
data = [NSData dataWithContentsOfURL:url options:0 error:nil];
[self saveToUserDefaults];
if(url == nil){
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
data = [defaults objectForKey:#"data"];
}
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
Try this one.
NSURL * url = [NSURL URLWithString:#"http://jamessuske.com/isthedomeopen/isthedomeopenGetData.php"];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSOperationQueue * newQueue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request
queue:newQueue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSArray * array = nil;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (error == nil) {
array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[defaults setObject:array forKey:#"data"];
} else {
array = [defaults objectForKey:#"data"];
}
NSLog(#"%#", array);
});
}];
Related
I am passing some parameters to wcf service to get the data, every thing running fine but i am not getting the data. i want to check how the parameters are calling the service and debug it. can any one let me know how to check it.
please find my code below for your reference.
NSArray *propertyNames = [NSArray arrayWithObjects:#"studentID", nil];
NSArray *propertyValues = [NSArray arrayWithObjects:#"E6A83233-7D7F-49AF-B54E-375BBF3E3E59", nil];
NSDictionary *properties = [NSDictionary dictionaryWithObjects:propertyValues forKeys:propertyNames];
// NSMutableDictionary* personObject = [NSMutableDictionary dictionary];
// [personObject setObject:properties forKey:#"person"];
NSMutableArray * arr;
//[arr addObject: personObject];
arr=[[NSMutableArray alloc]initWithObjects:properties, nil];
NSLog(#"%#",arr);
// NSString *jsonString = [personObject JSONRepresentation];
//NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError * error;
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://parentportal.technologyorg.com/parentportal.svc/GetSchoolEvents"]];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
[request setValue:jsonString forHTTPHeaderField:#"json"];
[request setHTTPMethod:#"Post"];
[request setHTTPBody:jsonData2];
NSLog(#"JSON String: %#",jsonString);
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned) {
//...handle the error
NSLog(#"error");
}
else {
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//...do something with the returned value
NSLog(#"RETVAL%#",retVal);
}
let me know if any thing went wrong
I make and app that the people download content and they can access it offline, it likes a catalogue. But Apple reject it because it baking up in iCloud i I'm doing the following but it seems not working.
Funciones.m
+ (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL {
const char* filePath = [[URL path] fileSystemRepresentation];
const char* attrName = "com.apple.MobileBackup";
u_int8_t attrValue = 1;
int result = setxattr(filePath, attrName, &attrValue, sizeof(attrValue), 0, 0);
return result == 0;
}
Update.m
- (void)updateImg:(NSString *)tipo {
//tomamos el ultimo update
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSTimeInterval time = [defaults doubleForKey:#"lastUpdate"];
NSLog(#"%f", time);
CatalogoAppDelegate *app = [[UIApplication sharedApplication] delegate];
NSString *post = [NSString stringWithFormat:#"lastUpdate=%f", time];
NSData *postData = [post dataUsingEncoding:NSISOLatin1StringEncoding allowLossyConversion:NO];
NSMutableURLRequest *urlRequest = [[[NSMutableURLRequest alloc] init] autorelease];
NSString *url = [NSString stringWithFormat:#"%#iPhone/update%#Img.php", app.serverUrl, tipo];
[urlRequest setURL:[NSURL URLWithString:url]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setHTTPBody:postData];
NSData *urlData;
NSURLResponse *response;
NSError *error;
urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
if(urlData) {
NSString *aStr = [[[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding]autorelease];
//NSLog(#"%#: %#", tipo, aStr);
NSArray *temp = [aStr componentsSeparatedByString:#";"];
//Direccionl Local de la APP
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
for (int i=0; i<[temp count]; i++) {
NSString *tempImg = [NSString stringWithFormat:#"%#", [temp objectAtIndex:i]];
//NSLog(#"%#", tempImg);
//pedimos cada url
NSURL *tempURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#images/%#/%#", app.serverUrl, tipo, tempImg]];
//[Funciones addSkipBackupAttributeToItemAtURL:tempURL];
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:tempURL]];
NSLog(#"%#images/%#/%#", app.serverUrl, tipo, tempImg);
NSString *pngFilePath = [NSString stringWithFormat:#"%#/%#", docDir, tempImg];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)];
[data1 writeToFile:pngFilePath atomically:YES];
NSURL *backUrl = [NSURL fileURLWithPath:pngFilePath];
[Funciones addSkipBackupAttributeToItemAtURL:backUrl];
}
}
[self performSelectorInBackground:#selector(finUpdate) withObject:nil];
}
Any idea what I am doing wrong?
Thanks
setxattr provides a result indicating success or an error, and Apple's addSkipBackupAttributeToItemAtURL: method checks for an error and passes this information back to your code. Your code simply ignores it. Start by determining if it's returning an error or not.
Maybe it's because your app is compatible with iOS 5.0.
Do not backup variable is only available since 5.1. Details here http://developer.apple.com/library/ios/#qa/qa1719/_index.html#//apple_ref/doc/uid/DTS40011342
SBJsonParser *parser= [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
//NSDictionary *object = [parser objectWithString:json_string error:nil];
NSArray *results = [parser objectWithString:json_string error:nil];
NSMutableArray *data = [NSMutableArray array]
self.data = data;
// check that what we've parsed is NSArray
if (results && [results isKindOfClass:[NSArray class]]) {
for (NSDictionary *sectionDict in results) {
if ([sectionDict isKindOfClass:[NSDictionary class]]) {
NSString *sectionTitle = [[sectionDict objectForKey:#"date"] description];
NSArray *events = [sectionDict objectForKey:#"events"];
if (date && events && [events isKindOfClass:[NSArray class]]) {
NSMutableArray *rows = [NSMutableArray arrayWithCapacity:[events count]];
for (NSDictionary *eventDict in events) {
if ([eventDict isKindOfClass:[NSDictionary class]]) {
[rows addObject:#"testRow"];
}
}
[data addObject:[NSDictionary dictionaryWithObjectsAndKeys: sectionTitle, #"section", rows, #"rows", nil]];
}
}
}
}
Now when i use this data in display on table view it show testRow on all cell but i want location on cell text and municipality in detailtext which come from JSON so how to do this
change
[rows addObject:#"testRow"];
to
[rows addObject:[eventDict objectForKey:#"location"]];
I'd suggest that you create a Event class with necessary attributes, such as location, municipality. Then you can do:
Event *event = [[Event alloc] init];
event.location = [eventDict objectForKey:#"location"];
event.municipality = [eventDict objectForKey:#"municipality"]]
[rows addObject:event];
[event release];
Then you can use the rows in your controller.
I have fetched the JSON data i want to store all the information like in a Book class object book and the use them by book.title etc.
I am using following code
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.krsconnect.no/community/api.html?method=bareListEventsByCategory&appid=620&category-selected=350&counties-selected=Vest-Agder,Aust-Agder"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *object = [parser objectWithString:json_string error:nil];
NSArray *results = [parser objectWithString:json_string error:nil];
NSDictionary *dictOne = [results objectAtIndex:0];
/*
NSArray *activitiesArray = [dictOne objectForKey:#"events"];
NSDictionary *dictTwo = [activitiesArray objectAtIndex:0];
NSLog(#"%# - %#", [dictOne objectForKey:#"date"]);
NSLog(#"%# - %#", [dictTwo objectForKey:#"affectedDate"]);
*/
appDelegate.books = [[NSMutableArray alloc] init];
NSArray *activitiesArray = [dictOne objectForKey:#"events"];
NSDictionary *dictTwo = [activitiesArray objectAtIndex:0];
NSLog(#"%# - %#", [dictOne objectForKey:#"date"]);
NSLog(#"%# - %#", [dictTwo objectForKey:#"affectedDate"]);
I want to do like this store the data in an array but its not working
NSArray *results = [parser objectWithString:json_string error:nil];
for (int i=0; i<[results count]; i++) {
Book *aBook = [[Book alloc] initWithDictionary:[results objectAtIndex:i]];
[appDelegate.books addObject:aBook];
[aBook release];
}
In UserDefault file I have six fields. I want to persist two field always and reset four other field in some scenario. What is best approach to handle this?
If your want the four field to reset with their default values.
And the default value may be an empty string ,
#define KDefault #""
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults)
{
[standardUserDefaults setObject:KDefault forKey:#"first"];
[standardUserDefaults setObject:KDefault forKey:#"two"];
[standardUserDefaults setObject:KDefault forKey:#"third"];
[standardUserDefaults setObject:KDefault forKey:#"four"];
[standardUserDefaults synchronize];
}
Edited:
For removing field rather than resetting: Use the below
[standardUserDefaults removeObjectForKey:#"first"];
[standardUserDefaults removeObjectForKey:#"two"];
[standardUserDefaults removeObjectForKey:#"third"];
[standardUserDefaults removeObjectForKey:#"four"];
[standardUserDefaults synchronize];
.you can use NSFileManager..sample code
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //1
NSString *documentsDirectory = [paths objectAtIndex:0]; //2
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"user.plist"]; //3
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path]) //4
{
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"user" ofType:#"plist"]; //5
[fileManager copyItemAtPath:bundle toPath: path error:&error]; //6
}
NSMutableDictionary *savedStock = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
//load from savedStock example int value
NSString* userName;
NSString* password;
NSString* pin;
userName = [savedStock objectForKey:#"name"];
password = [savedStock objectForKey:#"password"];
if([userName isEqualToString:#"some"] && [userName isEqualToString:#"some"] && [pin isEqualToString:#"some"])
{
[self setAdd];
}
else
{
[self pinAdd];
}