How to extract image from JSON response in iOS - ios

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;

Related

How to retrieve data from local file of json to a dictionary in Objective C iOS

I have trouble in retrieving the data from my JSON file to a dictionary and then I will access the values inside array of that dictionary to take the time and compare the time what I have done so far is that.
Note: I have multiple timings for one month.
in my viewDidLoad I have defined
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL fileURLWithPath:#"/Users/macbook/Desktop/Test/Test/myFile.json"];
NSString *fileContent = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
NSLog(#"Json data is here %#", fileContent);
saving data in dictionary
NSArray *data = [[theFeedString JSONValue] objectForKey:#"data"];
for (NSDictionray *dict in data) {
NSString *timings = [[dict objectForKey:#"timings"] intValue];
}
in my console I get all the data from my json and my json look like this
{
"data": [
{
"timings": {
"Sunrise": "07:14 (PKT)",
"Sunset": "18:15 (PKT)",
"Midnight": "00:45 (PKT)"
}
},
{
"timings": {
"Sunrise": "07:13 (PKT)",
"Sunset": "06:40 (PKT)",
"Midnight": "00:45 (PKT)"
}
}
]
}
You should do like this way, where Palettes.json is a local file.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Palettes" ofType:#"json"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
Let me know if there is any query.
UPDATE
According to your Output of JSON, you will get data array like this,
NSArray *data = json["data"];
[data enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) {
NSDictionary *timings = object["timings"];
NSString *sunrise = timings["Sunrise"];
}];
You can iterate through data array to get timings

Plist is not creating in Objective C

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)?

Fetch Images from NSArray of FilePath?

I am trying to fetch Images which i am storing in directory which i have shown in below code . I have tried a lot in StachOverFlow And Chats but not able to achieve the task . Actually i want to generate array of images from the array of filePath which are storing the path of images . Which i will show in UICollectionView . Please check my code and tell me what all can be done to achieve the needed . Thanks in advance
I have array of filepath already generated , i just want to fetch images from them and show it in grid view
-(void)plistRender{
// get paths from root direcory
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
// get documents path
NSString *documentsPath = [paths objectAtIndex:0];
// get the path to our Data/plist file
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"PhotoBucket.plist"];
//pngDATA.....
NSString *totalName = [NSString stringWithFormat:#"EGK_%# ", [NSDate date]];
PhotodocumentsPath = [paths objectAtIndex:0];
PhotofilePath = [PhotodocumentsPath stringByAppendingPathComponent:totalName]; //Add the file name
NSData *pngData = UIImagePNGRepresentation(printingImage);
//Write image to the file directory .............
[pngData writeToFile:[self documentsPathForFileName:PhotofilePath] atomically:YES];
[photos_URL addObject:PhotofilePath];
[photos addObject:totalName];
[grid_copy addObject:[NSNumber numberWithInteger:count]];
[grids addObject:whichProduct];
[Totalamount addObject:[NSNumber numberWithInteger:amt]];
NSDictionary *plistDictionary = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects: photos,grids,grid_copy,Totalamount,nil] forKeys:[NSArray arrayWithObjects: #"Photo_URL",#"Product",#"Copy",#"Amount", nil]];
NSString *error = nil;
// create NSData from dictionary
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:plistDictionary format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
// check is plistData exists
if(plistData)
{
// write plistData to our Data.plist file
[plistData writeToFile:plistPath atomically:YES];
}
else
{
NSLog(#"Error in saveData: %#", error);
}
NSString *string = [[NSString alloc] initWithData:plistData encoding:NSUTF8StringEncoding];
NSLog(#" plist Data %#", string);
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"PhotoBucket"]){
RecipeCollectionViewController *photoBucket = [segue destinationViewController];
NSLog(#"Prepare Segue%#",photoBucket.photoCollection);
NSLog(#"Number of photos %#",photos_URL);
NSMutableArray *imgQueue = [[NSMutableArray alloc] initWithCapacity:photos_URL.count];
for (NSString* path in photos_URL) {
[imgQueue addObject:[UIImage imageWithContentsOfFile:path]];
}
photoBucket.photoCollection = imgQueue;
}
}
try this
for(int i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
if ([[strFilePath pathExtension] isEqualToString:#"jpg"] || [[strFilePath pathExtension] isEqualToString:#"png"] || [[strFilePath pathExtension] isEqualToString:#"PNG"])
{
NSString *imagePath = [[stringPath stringByAppendingFormat:#"/"] stringByAppendingFormat:strFilePath];
NSData *data = [NSData dataWithContentsOfFile:imagePath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
}
}
}
Hi you can fetch like this:
NSArray *pathPlist1 =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryStr1 = [pathPlist1 objectAtIndex:0];
NSString *plistLocation1 =
[documentsDirectoryStr1 stringByAppendingPathComponent:#"ImageStorage"];
NSFileManager *filemgr;
NSArray *filelist;
int i;
filemgr =[NSFileManager defaultManager];
filelist = [filemgr contentsOfDirectoryAtPath:plistLocation1 error:NULL];
NSLog(#"filelist =%lu",[filelist count]);
cacheImagesArray=[[NSMutableArray alloc] init];
cacheImagesDataArray=[[NSMutableArray alloc] init];
for (i = 0; i < [filelist count]; i++){
NSLog(#"%#", [filelist objectAtIndex: i]);
NSString *imageName=[NSString stringWithFormat:#"%#",[filelist objectAtIndex: i]];
NSString *path=[NSString stringWithFormat:#"%#/%#",plistLocation1, [filelist objectAtIndex: i]];
NSLog(#"Path is =%#",path);
NSData* data = [NSData dataWithContentsOfFile:path];
[cacheImagesDataArray addObject:data];
[cacheImagesArray addObject:imageName];
}
thanks

Saving JSON file to iPhone

I want save json file from server each time, when user have internet connection to use it when iPhone doesnt have internet connection. But it doesn't working. Here is my code:
- (void)writeJsonToFile
{
//applications Documents dirctory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//live json data url
NSString *stringURL = #"http://volodko.info/ic/json.php";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
//attempt to download live data
if (urlData)
{
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"data.json"];
[urlData writeToFile:filePath atomically:YES];
}
//copy data from initial package into the applications Documents folder
else
{
//file to write to
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"data.json"];
//file to copy from
NSString *json = [ [NSBundle mainBundle] pathForResource:#"data" ofType:#"json" inDirectory:#"html/data" ];
NSData *jsonData = [NSData dataWithContentsOfFile:json options:kNilOptions error:nil];
//write file to device
[jsonData writeToFile:filePath atomically:YES];
}
}
try this . . .
- (void)writeJsonToFile
{
//applications Documents dirctory path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//live json data url
NSString *stringURL = #"http://volodko.info/ic/json.php";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
//attempt to download live data
if (urlData)
{
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"data.json"];
[urlData writeToFile:filePath atomically:YES];
}
//copy data from initial package into the applications Documents folder
else
{
//file to write to
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"data.json"];;
//file to copy from
NSString *json = [ [NSBundle mainBundle] pathForResource:#"data" ofType:#"json" inDirectory:#"html/data" ];
NSData *jsonData = [NSData dataWithContentsOfFile:json options:kNilOptions error:nil];
//write file to device
[jsonData writeToFile:filePath atomically:YES];
}
}
This works for me. Read the AFJSONRequestOperation guide. The code also checks if the json-file already have been cached.
NSString *path = #"http://volodko.info/ic/json.php";
NSURL *url = [[NSURL alloc] initWithString:path];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
id cachedJson = [[NSUserDefaults standardUserDefaults] valueForKey:path];
if (cachedJson) {
[self didUpdateJSON:cachedJson];
} else {
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
[self didUpdateJSON:JSON];
dispatch_async(dispatch_get_main_queue(), ^{
[[NSUserDefaults standardUserDefaults] setObject:JSON forKey:path];
[[NSUserDefaults standardUserDefaults] synchronize];
});
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
}
Fetch data from JSON parser and store it in an array. After that you can add it to a SQLite database.
You should create path in proper way
replace this
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"data.json"];
with
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"data.json"];
Anton , fetch the json data and store in the nsmutable array at the first time you Array hold the data when u run again ur array not a nil but replay the data to the second time ... and another way to store the data in local database...if u r needed to store the data..
but ur problem is solve for first one..ok best of luck..
Try using NSUserDefaults instead of writing this small JSON text to a file
- (void)writeJsonToFile
{
NSString *jsonString;
NSString *stringURL = #"http://volodko.info/ic/json.php";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if (urlData)
{
// JSON successfully downloaded, store it to user defaults
jsonString = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
[[NSUserDefaults standardUserDefaults] setValue:jsonString forKey:#"jsonString"];
}
else
{
// no urlData, using stored JSON
jsonString = [[NSUserDefaults standardUserDefaults] valueForKey:#"jsonString"];
}
}
possibly even better:
- (NSString *)getJSON
{
<the code above>
return jsonString;
}
and then use it in other functions as:
NSString *jsonString = [self getJSON];

Images downloading intermittently

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.

Resources