When i got my server response and trying to save that in plist, but plist file is not creating.
I have logged file path and dictionary contents but all these have data still plist not creating
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self sideMenu:#"ML"];
return YES;
}
this will call following method
-(void)sideMenu:(NSString *)title{
NSString *myRequestString = [[NSString alloc] initWithFormat:#"data=%#&deviceid=e8ef8c98262185ec",title];
NSData *myRequestData = [NSData dataWithBytes:[myRequestString UTF8String ] length: [ myRequestString length ] ];
NSMutableURLRequest *request = [ [ NSMutableURLRequest alloc ] initWithURL: [ NSURL URLWithString:SIDE_MENU]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody: myRequestData];
NSURLResponse *response;
NSError *err;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse:&response error:&err];
NSString* responseString = [[NSString alloc] initWithData:returnData encoding:NSNonLossyASCIIStringEncoding];
NSArray *myArray = [responseString componentsSeparatedByString:#"<!DOC"];
//NSLog(#"%#",myArray);
if (myArray != nil || [myArray count] > 0) {
NSData *data = [[[myArray objectAtIndex:0]stringByReplacingOccurrencesOfString:#"\n" withString:#""] dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
[self sideMenuFile:title :json];
}
}
-(NSString *)sideMenuFile:(NSString *)titleName :(NSDictionary *)dict{
NSString *filePath;
MyManager *sharedManager =[MyManager sharedManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if([titleName isEqualToString:#"ML"])
{ sharedManager.sideMenu = [[NSDictionary alloc]init];
sharedManager.sideMenu = dict;
filePath = [documentsDirectory stringByAppendingPathComponent:#"ML.plist"];
}else if ([titleName isEqualToString:#"HM"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"HM.plist"];
}else if ([titleName isEqualToString:#"PDC"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"PDC.plist"];
}else if ([titleName isEqualToString:#"SM"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"SM.plist"];
}else if ([titleName isEqualToString:#"GL"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"GL.plist"];
}else if ([titleName isEqualToString:#"CU"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"CU.plist"];
}else if ([titleName isEqualToString:#"BR"]){
filePath = [documentsDirectory stringByAppendingPathComponent:#"GL.plist"];
}
NSLog(#"%#",filePath); //printing path
[dict writeToFile:filePath atomically:YES];
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *plistName = #"GL";
NSString *finalPath = [basePath stringByAppendingPathComponent:
[NSString stringWithFormat: #"%#.plist", plistName]];
NSDictionary *dictww=[[NSDictionary alloc]initWithContentsOfFile:finalPath];
NSLog(#"dict%#",dictww); //printing nill
return filePath;
}
JSON file structure
{
sigallery = {
rows = (
{
active = True;
gallerytext = "<null>";
galleryurl = "assets/img/content-images/1.jpg";
moddt = "2016-07-19T12:28:18.873";
onclickurl = "testd.in";
settingsid = 1;
showfromdt = "1901-01-01T00:00:00.0";
showsequence = 1;
showuptodt = "2099-12-31T00:00:00.0";
videoimagebanneraudioswitch = I;
},
{
active = True;
gallerytext = "<null>";
galleryurl = "assets/img/content-images/2.jpg";
moddt = "2016-07-19T12:28:18.873";
onclickurl = "testd.in";
settingsid = 1;
showfromdt = "1901-01-01T00:00:00.0";
showsequence = 2;
showuptodt = "2099-12-31T00:00:00.0";
videoimagebanneraudioswitch = I;
}
)
}
}
Your code makes a number of non-optimal assumptions.
1)
Whenever you write out a file, you should always check for any error condition if it's available. NSDictionary's writeTo... methods do return Booleans whether the file has been written out or not, so you could do:
NSLog(#"%#",filePath); //printing path
BOOL success = [dict writeToFile:filePath atomically:YES];
if (success == false)
{
NSLog(#"did not successfully write dictionary to path %#", filePath);
} else {
// ... do everything else in here
}
2)
You write out files wih the format titleName + GL | PDC | SM.plist but when you try to read things back in, there is no titleName as part of the finalPath, so nothing lines up here.
3)
Also, why do you assume basePath is valid (it looks like it could be nil)?
Related
Basically I got response from server side and then i saved it in local file.Actually I fetched the response from server side and then saved into documents directory ,and now trying to fetch but it comes in NSString only ,i unable to get in NSDictionary....Here is following code
- (IBAction)loginButtonPressed:(id)sender
{
NSString *URLString = #"http://localhost/rest/login";
AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *params = #{#"username": userNameTxtField.text, #"password": pwdTextField.text};
NSLog(#"Parameters:\n%#",params);
[manager POST:URLString parameters:params progress:nil success:^(NSURLSessionDataTask *operation, id responseObject)
{
NSLog(#"Successfully Login ....: %#", responseObject);
NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
path = [NSString stringWithFormat:#"%#/sample.json", documents];
NSOutputStream *stream = [[NSOutputStream alloc] initToFileAtPath:path append:YES];
[stream open];
NSError *writeError = nil;
NSInteger bytesWritten = [NSJSONSerialization writeJSONObject:responseObject toStream:stream options:NSJSONWritingPrettyPrinted error:&writeError];
if ((bytesWritten = 0))
{
NSLog(#"Error writing JSON Data");
}
else{
NSLog(#"Sucessfuly saved data...");
}
[stream close];
NSLog(#"path is :%#",path);
} failure:^(NSURLSessionDataTask *operation, NSError *error)
{
NSLog(#"Error: %#", error);
}];
}
- (IBAction)fetch:(id)sender
{
NSError *deserializingError;
NSData *data=[NSData dataWithContentsOfFile:path];
NSString *jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&deserializingError];
NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"vaues are:%#",dict);
}
Your response object should be a type of NSDictionary. Therefore you can use its writeToFileAtPath method to save it to your documents directory.
When recreating the dictionary, you can use the NSDictionary's alloc and initWithContentsOfFile method to directly create a NSDictionary instance.
There are tons of posts on how to do that if you do a little Google search!
Try this!! It's working fine.
NSMutableDictionary *testStore = [[NSMutableDictionary alloc] init];
[testStore setObject:#"vignesh" forKey:#"username"];
[testStore setObject:#"password" forKey:#"password"];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:testStore // Here you can pass array or dictionary
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
NSString *jsonString;
if (jsonData) {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
//This is your JSON String
//NSUTF8StringEncoding encodes special characters using an escaping scheme
} else {
NSLog(#"Got an error: %#", error);
jsonString = #"";
}
[self writeStringToFile:jsonString];
NSLog(#"Your JSON String is %#", [self readStringFromFile]);
- (void)writeStringToFile:(NSString*)aString {
// Build the path, and create if needed.
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
if (![[NSFileManager defaultManager] fileExistsAtPath:fileAtPath]) {
[[NSFileManager defaultManager] createFileAtPath:fileAtPath contents:nil attributes:nil];
}
// Write to file
[[aString dataUsingEncoding:NSUTF8StringEncoding] writeToFile:fileAtPath atomically:NO];
}
- (NSString*)readStringFromFile {
// Build the path...
NSString* filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* fileName = #"bookmark.json";
NSString* fileAtPath = [filePath stringByAppendingPathComponent:fileName];
// read from file
return [[NSString alloc] initWithData:[NSData dataWithContentsOfFile:fileAtPath] encoding:NSUTF8StringEncoding];
}
static const char *dbPath = nil;
static sqlite3_stmt *ermsg = nil;
static sqlite3 *studs =nil;
static DatabaseOperation *_sharedInstances = nil;
#implementation DatabaseOperation
#synthesize databasePath;
+(DatabaseOperation*)sharedInstances{
if(!_sharedInstances){
_sharedInstances =[[super allocWithZone:nil]init];
}
return _sharedInstances;
}
+(id)allocWithZone:(struct _NSZone *)zone{
return [self sharedInstances];
}
-(id)init{
NSLog(#"Only first time Instances using Singleton:");
self =[super init];
if(self){
[self CreateDbpath];
}
return self;
}
-(BOOL)CreateDbpath{
NSArray *dbpaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docdir=[[NSString alloc]initWithString:[dbpaths objectAtIndex:0]];
self.databasePath =[[NSString alloc]initWithString:[docdir stringByAppendingPathComponent:#"Mindset.sqlite"]];
NSFileManager *flg = [NSFileManager defaultManager];
BOOL isSuccess = false;
if([flg fileExistsAtPath:databasePath]==NO){
char *ermsgss = nil;
char const *dbpathss =[self.databasePath UTF8String];
if(sqlite3_open(dbpathss, &studs)==SQLITE_OK){
char *sqlQuery ="create table if not exists emp(name text,city text,img blob)";
if(sqlite3_exec(studs, sqlQuery, nil, nil, &ermsgss)!=SQLITE_OK){
NSLog(#"Failed to create table:");
}
else{
NSLog(#"Successfully to create table:");
}
}
sqlite3_close(studs);
}
return isSuccess;
}
-(void)insertDatabaseValue:(DataManagers *)getInserted{
dbPath = [self.databasePath UTF8String];
if(sqlite3_open(dbPath, &studs)==SQLITE_OK){
NSString *sqlQuery=[[NSString alloc]initWithFormat:#"insert into emp values(?,?,?)"];
const char *_sqlQuery=[sqlQuery UTF8String];
if(sqlite3_prepare_v2(studs, _sqlQuery, -1, &ermsg, nil)==SQLITE_OK){
sqlite3_bind_text(ermsg, 1, [getInserted.userName UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(ermsg, 2, [getInserted.cityName UTF8String], -1, SQLITE_TRANSIENT);
NSData *jpegData =[[NSData alloc]init];
NSData *imgeData =UIImageJPEGRepresentation(getInserted.profileImg, 0.85f);
UIImage *imgesData =[UIImage imageWithData:imgeData];
CGRect rect = CGRectMake(0, 0, 185, 150);
UIGraphicsBeginImageContext(rect.size);
[imgesData drawInRect:rect];
UIImage *img =UIGraphicsGetImageFromCurrentImageContext()
;
UIGraphicsEndImageContext();
jpegData = UIImageJPEGRepresentation(img, 0.01f);
sqlite3_bind_blob(ermsg, 3, [jpegData bytes], [jpegData length], SQLITE_TRANSIENT);
if(sqlite3_step(ermsg)==SQLITE_DONE){
NSLog(#"Successfully inserted into db:");
}
else {
NSLog(#"Error %s",sqlite3_errmsg(studs));
}
}
sqlite3_close(studs);
sqlite3_finalize(ermsg);
}
}
-(NSMutableArray*)getAllData {
NSMutableArray *array =[[NSMutableArray alloc]init];
dbPath = [self.databasePath UTF8String];
if(sqlite3_open(dbPath, &studs)==SQLITE_OK){
NSString *sqlQuery =[[NSString alloc]initWithFormat:#"select * from emp"];
const char *_sqlQuery =[sqlQuery UTF8String];
if(sqlite3_prepare_v2(studs, _sqlQuery, -1, &ermsg, nil)==SQLITE_OK){
while (sqlite3_step(ermsg)==SQLITE_ROW) {
DataManagers *mgr =[[DataManagers alloc]init];
NSString *_Firstname = (const char*)sqlite3_column_text(ermsg, 0) ? [NSString stringWithUTF8String:(const char*)sqlite3_column_text(ermsg, 0)]:nil;
mgr.userName = _Firstname;
NSString *lastName =(const char*)sqlite3_column_text(ermsg, 1)?[NSString stringWithUTF8String:(const char*)sqlite3_column_text(ermsg, 1)]:nil;
mgr.cityName = lastName;
int imgBytes = sqlite3_column_bytes(ermsg, 2);
UIImage *img =[UIImage imageWithData:[NSData dataWithBytes:sqlite3_column_blob(ermsg, 2) length:imgBytes]];
mgr.profileImg = img;
[array addObject:mgr];
}
}
}
return array;
}
so I've been given a task of using a flickr API created by a lecturer, and we have to use it to populate a tableview of a particular user. I'm able to count the number of elements etc, but I can't figure out for the life of me how to actually call the image/photo element of the pair?
This is the code:
- (NSArray *) photosForUser: (NSString *) friendUserName
{
NSString *request = [NSString stringWithFormat: #"https://api.flickr.com/services/rest/?method=flickr.people.findByUsername&username=%#", friendUserName];
NSDictionary *result = [self fetch: request];
NSString *nsid = [result valueForKeyPath: #"user.nsid"];
request = [NSString stringWithFormat: #"https://api.flickr.com/services/rest/?method=flickr.photos.search&per_page=%ld&has_geo=1&user_id=%#&extras=original_format,tags,description,geo,date_upload,owner_name,place_url", (long) self.maximumResults, nsid];
result = [self fetch: request];
return [result valueForKeyPath: #"photos.photo"];
}
What is used to fetch the data:
- (NSDictionary *) fetch: (NSString *) request
{
self.apiKey = #"26225f243655b6eeec8c15d736b58b9a";
NSLog(#"self.APIKey = %#", self.apiKey);
NSString *query = [[NSString stringWithFormat: #"%#&api_key=%#&format=json&nojsoncallback=1", request, self.apiKey]
stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSURL *queryURL = [NSURL URLWithString: query];
NSData *responseData = [NSData dataWithContentsOfURL: queryURL];
if (!responseData)
return nil;
NSError *error = nil;
NSDictionary *jsonContent = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &error];
if (!jsonContent)
NSLog(#"Could not fetch '%#': %#", request, error);
return jsonContent;
}
Can anyone give me any pointers on how I can actually call the image?
Much appreciated.
edit: this is an NSLog output of what's in the JSON array received from the flickr API.
latestPhotos (
{
accuracy = 16;
context = 0;
dateupload = 1397679575;
description = {
"_content" = "<a href=\"https://www.flickr.com/photos/tanjabarnes/\">
};
farm = 3;
"geo_is_contact" = 0;
"geo_is_family" = 0;
"geo_is_friend" = 0;
"geo_is_public" = 1;
id = 13902059464;
isfamily = 0;
isfriend = 0;
ispublic = 1;
latitude = "34.062214";
longitude = "-118.35862";
owner = "66956608#N06";
ownername = Flickr;
"place_id" = "I78_uSpTWrhPjaINgQ";
secret = cc17afe1b3;
server = 2928;
tags = "panorama losangeles beverlyhills tanjabarnes";
title = blahlbah
woeid = 28288701;
}
)
You need to construct the URL of the image using the ids in your JSON array. Like this:
http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}.jpg
or
http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{secret}_[mstzb].jpg
or
http://farm{farm-id}.staticflickr.com/{server-id}/{id}_{o-secret}_o.(jpg|gif|png)
So in your example:
http://farm3.staticflickr.com/2928/13902059464_cc17afe1b3.jpg
Here's how you get to your images:
NSArray *photos = [self photosForUser:friendUserName];
for(NSDictionary *dictionary in photos) {
NSString *farmId = [dictionary objectForKey:#"farm"];
NSString *serverId = [dictionary objectForKey:#"server"];
NSString *photoId = [dictionary objectForKey:#"id"];
NSString *secret = [dictionary objectForKey:#"secret"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://farm%#.staticflickr.com/%#/%#_%#.jpg", farmId, serverId, photoId, secret]];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
// Do something with your image here
}
Reference: https://www.flickr.com/services/api/misc.urls.html
I am parsing JSON from a webService which gives me image , text , etc.The text can be extracted , but how do I get the image out of it?
This is how the JSON response looks like.
[
{ "photo": "23_841676772.jpg",
"date": "2013-06-06 08:11:15",
"tags": "",
"ID_article": "1",
"commentcount": "5"
},
]
And I was trying to set it like this in tableView:cellForRow method which doesn't work.
NSMutableDictionary *tempDict3 = [self.jsonArray objectAtIndex:indexPath.row];
cell.blogImageView.image = [UIImage imageNamed:[tempDict3 objectForKey:#"photo"]];
I have used static json you can replace str with your json url.
NSString *Str =[NSString stringWithFormat:#"[{\"photo\": \"23_841676772.jpg\",\"date\":\"2013-06-06 08:11:15\",\"tags\": \"\",\"ID_article\": \"1\",\"commentcount\": \"5\"},{\"photo\": \"dfdgfdgd.jpg\",\"date\":\"2013-06-06 08:11:15\",\"tags\": \"\",\"ID_article\": \"1\",\"commentcount\": \"5\"}]"];
NSDictionary *catgDict = [NSJSONSerialization JSONObjectWithData:[Str dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
for(NSDictionary *dict in catgDict)
{
NSLog(#"dd: %#",dict);
NSLog(#"Photo: %#",[dict valueForKey:#"photo"]);
}
ask your web service team to add another tag as "image_url" to your response so that you can convert the image url to image. If they say we can't give it for security reason, then the only option left is hard code the path and append the "image name" to it so that you will have complete url of image and now you can convert it into image.
For extercating the Photo name from the JASON response you can use this code
JSONResponse : [
{ "photo": "23_841676772.jpg",
"date": "2013-06-06 08:11:15",
"tags": "",
"ID_article": "1",
"commentcount": "5"
},
]
Make a Array object in .h file
#interface ViewController : UIViewController
{
NSMutableArray * photoNameData;
}
And in .m file
photoNameData =[[NSMutableArray alloc] init];
NSMutableArray * tmpAry = JSONResponse;
if (tmpAry.count !=0) {
for (int i=0; i<tmpAry.count; i++) {
NSMutableDictionary * tmpDictn = [tmpAry objectAtIndex:i];
[photoNameData addObject:[tmpDictn objectForKey:#"photo"]];
}
}
You can use the code below to download the image in document directory.
for (int i=0; i<photoNameData.count; i++) { //updated here
//First check that document directory contain image or not
NSString* tmpStr = [photoNameData objectAtIndex:i]; // used the photoNameData to get image name
NSString* tmpImgURL = [NSString stringWithFormat:#"%#%#",#"http://www.my server.com/web_services/photos/",tmpStr]; //merge the image name and url
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents = [paths objectAtIndex:0];
NSString* foofile = [documents stringByAppendingPathComponent:tmpStr];
BOOL imageExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
// if image not exist than download it
if (!imageExists) {
NSLog(#"%# not exist",tmpImgURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:tmpImgURL] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:10.0];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *err){
if (!err && data) {
//NSLog(#"data : %#",data);
NSString *finalPath = [documents stringByAppendingPathComponent:tmpStr];
NSLog(#"finalPath : %#",finalPath);
[data writeToFile:finalPath atomically:YES];
}else{
NSLog(#"err : %#",err);
}
}];
}
}
And you can use this image using this code..
NSString* tmpStr = [photoNameData objectAtIndex:indexPath.row]; //get the image name from photoNameData
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
UIImage * image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:#"%#/%#",documentsDirectoryPath, tmpStr]];
cell.blogImageView.image = image;
In my iOS app I'm using the weather APIs of worldweatheronline.com but I get a random "EXC_BAD_ACCESS" error oh this row (not always but sometimes) :
temperature.text = [NSString stringWithFormat:#"%# °C", tempC];
Here is my code:
- (void)showWeatherFor:(CLLocation *)newLocation
{
NSString *myRequestString = [[NSString alloc] initWithFormat:#"http://api.worldweatheronline.com/free/v1/weather.ashx?q=%f,%f&format=json&num_of_days=5&key=ydvgep8jn5m846upd8kb2qp6", newLocation.coordinate.latitude, newLocation.coordinate.longitude];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:myRequestString]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *JsonString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *theDictionary = [NSDictionary dictionaryWithJSONString:JsonString error:&error];
NSDictionary *data = [theDictionary objectForKey:#"data"];
NSArray *currentDictionary = [data objectForKey:#"current_condition"];
NSDictionary *temp = [currentDictionary objectAtIndex:0];
if ([temp objectForKey:#"temp_C"] == nil || [temp objectForKey:#"temp_F"] == nil)
{
return;
termometro.alpha = 0;
}
else
{
if (temp != nil)
{
if ([mainDelegate.gradi isEqualToString: #"°C"])
{
NSNumber *tempC = [temp objectForKey:#"temp_C"];
temperature.text = [NSString stringWithFormat:#"%# °C", tempC];
mainDelegate.temperature = [[temp objectForKey:#"temp_C"]intValue];
}
else
{
NSNumber *tempF = [temp objectForKey:#"temp_F"];
temperature.text = [NSString stringWithFormat:#"%# °F", tempF];
mainDelegate.temperature = [[temp objectForKey:#"temp_F"]intValue];
}
termometro.alpha = 1;
}
}
}
I have an iPad app which connects to a C# web service to download documents and images.
If I run it as a fresh install on the iPad, it downloads the expected documents and images. If I upload a new document and relaunch the app, it downloads it as expected. However, if I upload a new image to the server and run it again, it doesn't download the new image.
Here is the code for checking and downloading documents:
- (void)checkFiles:(NSString *)sessionID
{
fileList = [[NSMutableString alloc] init];
// get contents of doc directory
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [directoryPaths objectAtIndex:0];
NSString *downloadsFolderString = [documentsDirectory stringByAppendingPathComponent:DOWNLOADS_FOLDER];
NSError *error = nil;
NSString* file;
NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:downloadsFolderString];
while (file = [enumerator nextObject])
{
BOOL isDirectory = NO;
[[NSFileManager defaultManager] fileExistsAtPath: [NSString stringWithFormat:#"%#/%#", downloadsFolderString,file]
isDirectory: &isDirectory];
if ([file rangeOfString:#"LinkIcons"].location == NSNotFound)
{
if (!isDirectory)
{
[fileList appendString:[NSString stringWithFormat:#"%#|", file]];
}
}
}
// create string to send to server
NSString *post = [NSString stringWithFormat:#"sessionID=%#&fileList=%#&dateTime=%#&userID=%#", sessionID, fileList, timeOpened, userID];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *comparisonURLString = SERVER_COMPARE_URL_STRING;
NSURL *comparisonURL = [NSURL URLWithString:comparisonURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:comparisonURL];
[request setHTTPMethod:#"POST"];
[request addValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
// get response - list of files for download
NSHTTPURLResponse *urlResponse = nil;
error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
if (responseData)
{
NSString *requiredFilesList = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// remove xml nodes from list
NSArray *lines = [requiredFilesList componentsSeparatedByString: #"\n"];
if (lines.count > 2)
{
// create sub array without xml nodes
NSRange theRange;
theRange.location = 2;
theRange.length = [lines count] -3;
numberOfFilesToBeDownloaded = theRange.length;
if (numberOfFilesToBeDownloaded <= 0)
{
_jobStatusLabel.text = #"Documents up to date";
}
if (numberOfFilesToBeDownloaded > 0)
{
NSArray *subArray = [lines subarrayWithRange:theRange];
[self getFiles:subArray];
}
}
}
[self checkLinks];
}
and:
- (void)getFiles:(NSArray *)filenames
{
downloadManager = [[DownloadManager alloc] init];
downloadManager.delegate = self;
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *downloadFolder = [documentsPath stringByAppendingPathComponent:#"downloads"];
for (NSString *filename in filenames)
{
NSString *downloadFilename = [downloadFolder stringByAppendingPathComponent:filename];
NSString *baseUrlString = SERVER_DOWNLOAD_URL_STRING;
NSString *finalUrlString = [baseUrlString stringByAppendingPathComponent:[filename stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[downloadManager addDownload:downloadFilename fromUrl:[NSURL URLWithString:finalUrlString] ];
[self notifyServerFileDownloaded:filename];
}
}
And this is the corresponding code for the images:
- (void) checkLinks
{
NSMutableString *linkListOnDevice = [[NSMutableString alloc] init];
NSMutableArray *globalLinksArray = [[[NSUserDefaults standardUserDefaults] objectForKey:#"globalLinksArray"]mutableCopy];
if(globalLinksArray != nil)
{
NSLog(#"Links Array found. Contents: %#", globalLinksArray);
}
else
{
globalLinksArray = [[NSMutableArray alloc] initWithCapacity:0];
}
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [directoryPaths objectAtIndex:0];
NSString *downloadsFolderString = [documentsDirectory stringByAppendingPathComponent:DOWNLOADS_FOLDER];
NSString *LinksFolderString = [downloadsFolderString stringByAppendingPathComponent:#"/LinkIcons"];
NSError *error = nil;
NSString* file;
NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:LinksFolderString];
while (file = [enumerator nextObject])
{
BOOL isDirectory = NO;
[[NSFileManager defaultManager] fileExistsAtPath: [NSString stringWithFormat:#"%#/%#",downloadsFolderString,file]
isDirectory: &isDirectory];
if (!isDirectory)
{
[linkListOnDevice appendString:[NSString stringWithFormat:#"%#|", file]];
}
}
// create string to send to server
NSString *post = [NSString stringWithFormat:#"iconsList=%#&userID=%#", linkListOnDevice, userID];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *comparisonURLString = SERVER_COMPARE_LINK_ICONS_URL_STRING;
NSURL *comparisonURL = [NSURL URLWithString:comparisonURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:comparisonURL];
[request setHTTPMethod:#"POST"];
[request addValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
// get response - list of files for download
NSHTTPURLResponse *urlResponse = nil;
error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *requiredIconsList = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// remove xml nodes from list
NSArray *lines = [requiredIconsList componentsSeparatedByString: #"\n"];
// create sub array without xml nodes
NSRange theRange;
theRange.location = 2;
theRange.length = [lines count] -3;
numberOfFilesToBeDownloaded += theRange.length;
NSArray *linkSubArray = [lines subarrayWithRange:theRange];
NSMutableArray *iconsArray = [[NSMutableArray alloc] initWithCapacity:0];
NSString *linkDetail;
for (linkDetail in linkSubArray) {
[globalLinksArray addObject:linkDetail];
}
[[NSUserDefaults standardUserDefaults] setObject:globalLinksArray forKey:#"globalLinksArray"];
[[NSUserDefaults standardUserDefaults] synchronize];
// separate file for download from rest of string
for (NSString *linkString in linkSubArray)
{
NSArray *spltArray = [linkString componentsSeparatedByString:#"^"];
NSString *linkIconString = spltArray[3];
[iconsArray addObject:linkIconString];
}
[self getLinks:iconsArray];
}
and:
- (void) getLinks: (NSMutableArray *) linkList
{
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *downloadFolder = [documentsPath stringByAppendingPathComponent:#"downloads"];
for (NSString *filename in linkList)
{
NSString *downloadFilename = [downloadFolder stringByAppendingPathComponent:filename];
NSString *baseUrlString = SERVER_DOWNLOAD_URL_STRING;
NSString *finalUrlString = [baseUrlString stringByAppendingPathComponent:[filename stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[downloadManager addDownload:downloadFilename fromUrl:[NSURL URLWithString:finalUrlString] ];
}
}
Can anyone shed any light on why this works for documents but for images only on first run but not subsequently?
1) write this on didFinishLaunchingWithOptions method
NSString *savedValue = [[NSUserDefaults standardUserDefaults]
stringForKey:#"FirstTime"];
if (![savedValue isEqualToString:#"1"])
{
//Call for download image OR image downloading coding.
}
2) When image downloading complete then store value in NSUserDefaults
NSString *valueToSave = #"1";
[[NSUserDefaults standardUserDefaults]
setObject:valueToSave forKey:#"FirstTime"];
3) when next time your app is run then (1) condition is true and it not download image next time. If you want to download this then delete your app from simulator or device and clean then run the app.