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];
Related
I have a problem while trying to session.dataTaskWithRequest in a function to read gzip from URL.
The server side changes .gzip to .bin and stores the file.
I want to read the file with .bin. However, The network connection was lost.
However, a The network connection was lost error will occur.
Could you tell me how to solve this problem?
Server side file name: xxx.bin (this bin file is a gzip file.)
Following the code:
NSURLSessionConfiguration *config = [NSURLSessionConfiguration
defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURL *url = [NSURL URLWithString:#"http://...../xxx.bin"];
NSURLSessionDataTask *task = [session dataTaskWithURL: url
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"error [%#]", [error localizedDescription]);
}
else {
NSLog(#"success");
}
}];
[task resume];
You can try two steps of codes to download and extract zip files.
//Fetching zip file from server
-(void)dataSyncFileDonload{
NSString *stringURL = [NSString stringWithFormat:#"http://yourzipfilecontainedURL"];
stringURL = [stringURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
[self extractDownloadedZipFile:urlData];
}
//File Extraction from Zip file
-(void)extractDownloadedZipFile:(NSData *)data {
//If you are using SQlite and storing in local directory for extraction
NSData *outputData = [data gunzippedData];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSString *dataPath = [path stringByAppendingPathComponent:#"myAppDB.sql"];
NSString *dataPath1 = [path stringByAppendingPathComponent:#"myAppDB.sql.gz"];
dataPath = [dataPath stringByStandardizingPath];
[outputData writeToFile:dataPath atomically:YES];
[data writeToFile:dataPath1 atomically:YES];
[self readExtractedFile:dataPath];
}
//Read upzip file
-(void)readExtractedFile:(NSString *)filepath loaderPercent:(float)loaderPercent loaderTo:(float)loaderTo{
NSData *fileData = [NSData dataWithContentsOfFile:filepath];//destinationPath
NSString *fileString = [[NSString alloc] initWithData:fileData encoding:NSASCIIStringEncoding];
NSArray* allLinedStrings = [fileString componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];
//You can use you data now.
}
I want to upload voice recording on server.
My file url is:
file:///Users/xantatech/Library/Developer/CoreSimulator/Devices/77F4D768-1F04-4390-B60F-F1FE79388653/data/Containers/Data/Application/87C457FA-1A9F-4CA9-A651-6A3D411A0B7E/Documents/myAudio0.mp3
My Code is:
NSData* data = [NSData dataWithContentsOfURL:audioURL options:NSDataReadingUncached error:&error];
But the data is nil.
Please try below code
NSString *audioURLString = #"file:///Users/xantatech/Library/Developer/CoreSimulator/Devices/77F4D768-1F04-4390-B60F-F1FE79388653/data/Containers/Data/Application/87C457FA-1A9F-4CA9-A651-6A3D411A0B7E/Documents/myAudio0.mp3";
NSString *sendStr = [[audioURLString absoluteString] stringByReplacingOccurrencesOfString:#"file:///private" withString:#""];
NSData *data = [[[NSData dataWithContentsOfFile:sendStr]]];
Good luck.....
Use this code for get data from Document folder:
if([[NSFileManager defaultManager] fileExistsAtPath:filepath)
{
NSData *data = [[NSFileManager defaultManager] contentsAtPath:filepath];
}
else
{
NSLog(#"File not exits");
}
You just need to do:
NSURL *imgPath = [[NSBundle mainBundle] URLForResource:#"test" withExtension:#"png"];
NSString *path = [imgPath absoluteString];
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:path];
Try this
NSData* data =[[NSData alloc]init];
data = [NSData dataWithContentsOfFile:[NSURL URLWithString:path]];
After run:
file:///Users/xantatech/Library/Developer/CoreSimulator/Devices/77F4D768-1F04-4390-B60F-F1FE79388653/data/Containers/Data/Application/"87C457FA-1A9F-4CA9-A651-6A3D411A0B7E"/Documents/myAudio0.mp3
The Bold text "87C457FA-1A9F-4CA9-A651-6A3D411A0B7E" may change;
You should always use the method to get the path in sandBox:
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:#"myAudio0.mp3"];
You can use this:
NSData *data = [NSData dataWithContentsOfURL:yourURL];
I'm having troubles decrypting pdf files and displaying them with presentViewController after they are encrypted.
When I download the pdf files, they are being encrypted like this:
NSData *pdfData = [[NSFileManager defaultManager] contentsAtPath:filePathDocumetFolder];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents = [paths objectAtIndex:0];
NSString *docFolder = [NSString stringWithFormat:#"/Documents/%#", documentFilePath];
NSString *filePath = [documents stringByAppendingPathComponent:docFolder];
NSString *pdfName = [NSString stringWithString:filename ];
NSError *error;
NSData *encryptedPdf = [RNEncryptor encryptData:pdfData withSettings:kRNCryptorAES256Settings password:#"A_SECRET_PASSWORD" error:&error];
if(error){
NSLog(#"error: %#", error);
}
NSLog(#"where?? FileTra%#", filePath);
[encryptedPdf writeToFile:[filePath stringByAppendingPathComponent:pdfName] atomically:YES];
I know that this encryption above works, as when I browse the filesystem with iExplorer, I cannot open the files because they are protected.
In my DocumentHandle controller I'm trying to decrypt them so that they can be viewed:
NSDictionary* dict = [command.arguments objectAtIndex:0];
NSString* urlStr = dict[#"url"];
NSURL* url = [NSURL URLWithString:urlStr];
NSString* fileName = [url path];
NSString* path = [NSTemporaryDirectory() stringByAppendingPathComponent: fileName];
NSData *dataEn = [[NSFileManager defaultManager] contentsAtPath:[path stringByAppendingPathComponent:fileName]];
NSLog(#"this to decrypt%#", [path stringByAppendingPathComponent:fileName]);
NSData *decryp = [RNDecryptor decryptData:dataEn withSettings:kRNCryptorAES256Settings password:#"A_SECRET_PASSWORD" error:nil];
[decryp writeToURL:[[NSURL alloc] initFileURLWithPath:path] atomically:YES];
if(decryp){
NSLog(#"decrypted");
}else{
NSLog(#" not decrypted");
}
weakSelf.fileUrl = [[NSURL alloc] initFileURLWithPath:path];
For some reason, the pdf files are not being decrypted and I'm being presented with a blank file even thought I'm receiving NSLog as decrypted :(
Can anyone help me please? thank you
Hi I am getting single image from server using url in iOS.
my code is like this
- (IBAction)overlaysClicked:(id)sender
{
NSLog(#"overlays Clicked");
request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://sukhada.co.in/img/overlays/neon/ov1.png"]];
[NSURLConnection connectionWithRequest:request delegate:self];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:#"image.jpg"];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://sukhada.co.in/img/overlays/neon/ov1.png"]];
[thedata writeToFile:localFilePath atomically:YES];
UIImage *img = [[UIImage alloc] initWithData:thedata];
self.overlayImgView.image=img;
}
To get multiple images from server my code like this
NSURL *myUrl = [NSURL URLWithString:#"http://sukhada.co.in/img/overlays/neon.zip"];
NSURLRequest *myRequest = [NSURLRequest requestWithURL:myUrl cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
myData = [[NSMutableData alloc] initWithLength:0];
NSURLConnection *myConnection = [[NSURLConnection alloc] initWithRequest:myRequest delegate:self startImmediately:YES];
//my Array is like this in viewDidload
self.overlaysImgsArray = [[NSMutableArray alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://sukhada.co.in/img/overlays/neon.zip"]];
NSLog(#"urls is %#",overlaysImgsArray);
for (int i=0; i<[overlaysImgsArray count]; i++)
//download array have url links
{
NSURL *URL = [NSURL URLWithString:[overlaysImgsArray objectAtIndex:i]];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]initWithURL:URL];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if([data length] > 0 && [[NSString stringWithFormat:#"%#",error] isEqualToString:#"(null)"])
{
//make your image here from data.
UIImage *imag = [[UIImage alloc] initWithData:[NSData dataWithData:data]];
NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [array objectAtIndex:0];
NSString *imgstr=[NSString stringWithFormat:#"%d",i];
NSString *pngfilepath = [NSString stringWithFormat:#"%#sample%#.png",docDir,imgstr];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(imag)];
[data1 writeToFile:pngfilepath atomically:YES];
}
else if ([data length] == 0 && [[NSString stringWithFormat:#"%#",error] isEqualToString:#"(null)"])
{
NSLog(#"No Data!");
}
else if (![[NSString stringWithFormat:#"%#",error] isEqualToString:#"(null)"]){
NSLog(#"Error = %#", error);
}
}];
}
}
But this is not working for me please anybody suggest me how to get multiple images from server using one url which contains all the images. Please anybody
thank you in advance
In your case you can try like this
first you need to save all the 10 image in directory and the fetch one by one as your requirement .this code save all image from your url
try this
- (IBAction)overlaysClicked:(id)sender {
//Note all your image saved with ov1.png,ov2.png......& so .
for (int i=1; i<=10; i++) {
NSString *st2=#"ov";
NSString *st1=#"http://sukhada.co.in/img/overlays/neon/ov";
NSString *imageN=[st2 stringByAppendingString:[NSString stringWithFormat:#"%d",i]];
NSString *imgNameforkey=[imageN stringByAppendingString:#".png"];
NSString *url=[st1 stringByAppendingString:[NSString stringWithFormat:#"%d",i]];
NSString *imgname=[url stringByAppendingString:#".png"];
NSLog(#" all=%#",imgname);
NSLog(#"overlays Clicked");
request = [NSURLRequest requestWithURL:[NSURL URLWithString:imgname]];
[NSURLConnection connectionWithRequest:request delegate:self];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:imgname];
NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgname]];
[thedata writeToFile:localFilePath atomically:YES];
UIImage *img = [[UIImage alloc] initWithData:thedata];
NSLog(#"imgs %#",img);
// self.overlayImgView.image=img;
}
}
here you can see all image saved
fetch the image
using loop or with name
NSArray *directoryPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *imagePath = [directoryPath objectAtIndex:0];
imagePath= [imagePath stringByAppendingPathComponent:#"ov1.png"];
NSData *data = [NSData dataWithContentsOfFile:imagePath];
UIImage *img = = [UIImage imageWithData:data];
download a zip file from url and save it .use this code inside the button action. no need for loop now. try this
- (IBAction)overlaysClicked:(id)sender {
dispatch_queue_t queue = dispatch_get_global_queue(0,0);
dispatch_async(queue, ^{
NSLog(#"Beginning download");
NSString *stringURL = #"http://sukhada.co.in/img/overlays/neonra.zip";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
//Find a cache directory. You could consider using documenets dir instead (depends on the data you are fetching)
NSLog(#"Got the data!");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
//Save the data
NSLog(#"Saving");
NSString *dataPath = [path stringByAppendingPathComponent:#"img.zip"];
dataPath = [dataPath stringByStandardizingPath];
[urlData writeToFile:dataPath atomically:YES];
});
}
and check you will get img.zip file
I am building an article reading iOS app.
I have a .json file in match folder named as Data.json
I am not able to write data into it.
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 = ysURL;
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
//file to write to
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, #"Data.json"];
//attempt to download live data
if (urlData) {
[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:#"/match/Data.json"];
NSData *jsonData = [NSData dataWithContentsOfFile:json options:kNilOptions error:nil];
//write file to device
[jsonData writeToFile:filePath atomically:YES];
}
}
Try using NSStrings method to write the file, and check your error code:
NSURL *fileUrl = [[NSBundle mainBundle] URLForResource: #"Data" withExtension:#"json"];
NSError * error;
[json writeToURL:fileUrl atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#",error.localizedDescription);
can you tell us more about the problem you have ?
1) You don't have to redefine the filePath in the else because you already did before.
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, #"Data.json"];
And you should use stringByAppendingPathComponent which automaticaly add the / you will need or not :
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Data.json]
2) Are you sure your Data.json is include in your project ? do you get a nil ?
NSString *json = [[NSBundle mainBundle] pathForResource:#"Data" ofType:#"json" inDirectory:#"/match/Data.json"];
3) For the problem of not load : </Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.pl​atform/Developer/SDKs/iPhoneSimulator7.1.sdk/System/Library/AccessibilityBundles/CertUIFramework.axbundle> (not loaded)
Cannot find executable for CFBundle CertUIFramework.axbundle