Download and replace file in directory - ios

I am trying download a file from an URL, but the problem is when ever I open the downloaded file it opens the last file which I downloaded before! I mean if I download image1.png and open it , then try to download and replace image2.png,when I am going to open the last downloaded file, the file still image1.png !
Here is my code :
- (void)downloadDataFromMac {
[MBProgressHUD showHUDAddedTo:self.view animated:nil];
NSString *replace = [absulutePath stringByReplacingOccurrencesOfString:#" " withString:#"%20" options:NSLiteralSearch range:NSMakeRange(0, [absulutePath length])];
pathWithData = [NSString stringWithFormat:#"http://192.168.1.36:8888/?req=getimg&key=%#",replace];
NSURL *URL = [NSURL URLWithString:pathWithData];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSProgress *progress;
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *documentsDirectoryURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]objectAtIndex:0];
return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(#"File downloaded to: %#", filePath);
//Hide HUD
[MBProgressHUD hideHUDForView:self.view animated:YES];
self.documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:filePath];
[self.documentInteractionController setDelegate:self];
[self.documentInteractionController presentPreviewAnimated:YES];
}];
[downloadTask resume];
}
any help ?,thanks.

Try this:
//Saving images
-(BOOL) saveImage:(UIImage *) image filePath:(NSString *) filePath
{
// Creating path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *fileFullPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:filePath];
// Saving image.
BOOL success = [UIImageJPEGRepresentation(image, 1.0) writeToFile:fileFullPath atomically:YES];
if (!success) {
NSLog(LogPropertyError, #"Couldn't save image to disk %#",fileFullPath);
}
return success;
}

Related

can't download bin file for gzip file

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.
}

How to Sync my data saved in plist with web server?

i am using plist to save my data locally when network connection is not available, and when network is available i want to sync my locally saved data to the web server.  
i am using this code. but i dont know whether the data is saved in server or not. 
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://example url"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:#"file://my plist file"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];
i am assigning my api to the URL in which i want to save the data of plist, and my plist to the filepath in which my data is already saved. can anyone solve this issue.
I think you use normal API Call to stored pList file to a server. Becuase when you read plist file, your will data in NSDictionary and you send it server to store.
To read value from plist:
NSString* plistPath = [[NSBundle mainBundle] pathForResource:#"YOUR_PLIST_NAME" ofType:#"plist"];
NSDictionary *dicData = [NSDictionary dictionaryWithContentsOfFile:plistPath];
To send this dictionary to server, you can use AFNetworking.
To Stored valude into plist:
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = paths.firstObject;
NSString *plistPath = [documentsPath stringByAppendingPathComponent:#"File.plist"];
NSError *writeError = nil;
NSDictionary *finalDict = #{#"Objects": objects};
NSData *plistData = [NSPropertyListSerialization dataWithPropertyList:finalDict format:NSPropertyListXMLFormat_v1_0 options:NSPropertyListImmutable error:&writeError];
if(plistData){
[plistData writeToFile:plistPath atomically:YES];
}
else {
NSLog(#"Error in saveData: %#", error);
}

accessing the video inside .tmp

this code works and saves the downloaded file to camera roll if the file is an image but it doesn't save it when it's a video file .
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
NSData * data = [NSData dataWithContentsOfURL:location];
UIImage * image = [UIImage imageWithData:data];
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
UISaveVideoAtPathToSavedPhotosAlbum(location.path, self, #selector(video:didFinishSavingWithError: contextInfo:), nil);
dispatch_async(dispatch_get_main_queue(), ^{
[self.ProgressView setHidden:NO];
});
}
when I get the path of downloaded file it is a temp file like this:
/private/var/mobile/Containers/Data/Application/DE97D98D-760F-48DC-AFBB-C61C5E3185A0/tmp/CFNetworkDownload_5DOCCe.tmp
and I think since UISaveVideoAtPathToSavedPhotosAlbum wants target video's path to save the reason it doesn't work is that it cannot access the video file inside .tmp
please help! it's been quite a while I'm struggling with this.
try to use the ALAssestsLibrary
#property (strong, nonatomic) ALAssetsLibrary *library;
NSURL *videoURL = [NSURL URLWithString:videoURLString];
dispatch_async(dispatch_get_main_queue(), ^{
NSURLRequest *request = [NSURLRequest requestWithURL:videoURL];
AFURLConnectionOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:videoName];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
NSLog(#"downloadComplete! is %f", (float)totalBytesRead / totalBytesExpectedToRead);
}];
[operation setCompletionBlock:^{
NSLog(#"downloadComplete!");
[self.library writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:filePath] completionBlock:^(NSURL *assetURL, NSError *error) {
if (error) {
NSLog(#"%#", error.description);
}
else {
NSLog(#"Done :)");
NSString *fileDownloadStatus = [NSString stringWithFormat:#"Downloading of %# Finished", videoName];
[SVProgressHUD showImage:[UIImage imageNamed:#"Mp4_Icon"] status:fileDownloadStatus];
}
}];
}];
[operation start];
});
I found my solution:
NSData * data = [NSData dataWithContentsOfURL:location];
[[NSFileManager defaultManager] moveItemAtURL:location toURL:[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] error:nil];
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString * FilePath = [documentsDirectory stringByAppendingPathComponent:jsonTitle];
[data writeToFile:FilePath atomically:YES];
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(FilePath)) {
UISaveVideoAtPathToSavedPhotosAlbum(FilePath, nil, nil, nil);
} else {
NSLog(#"error");
}
NSFileManager * removeDownloadAfterSave;
[removeDownloadAfterSave removeItemAtPath:FilePath error:nil];

How to save the live/animated wallpaper

I am making an app of live photo/wallpaper. I am downloading image and .mov file from server. Now I am stuck to saving these files in document directory. How can I store the live wallpaper in document directory. Is anyone have idea about this please tell me. Here is my code
SDWebImageDownloader *downloader = [SDWebImageDownloader sharedDownloader];
[downloader downloadImageWithURL:[NSURL URLWithString:imgFile]
options:0
progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
if (image && finished) {
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [searchPaths objectAtIndex:0];
NSString* photoPath = [documentPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.JPG",strImg]];
[data writeToFile:photoPath atomically:YES];
}
}];
NSURL *URL = [NSURL URLWithString:str];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * downloadProgress){
NSLog(#"%f",downloadProgress.fractionCompleted);
NSString * str = [NSString stringWithFormat:#"%.2f",downloadProgress.fractionCompleted];
NSDictionary * infoDict = #{#"Download": str,
#"id":uniqId};
[[NSNotificationCenter defaultCenter]
postNotificationName:#"DownloadNotification"
object:self userInfo:infoDict];
}destination:^ NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [searchPaths objectAtIndex:0];
NSString* videoPath = [documentPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.MOV",strImg]];
NSURL *videoUrl =[NSURL URLWithString:videoPath];
NSLog(#"%#",[videoUrl URLByAppendingPathComponent:videoPath]);
return videoUrl;
} completionHandler:^(NSURLResponse* response, NSURL *filePath, NSError *error) {
if(error)
{
NSLog(#"File Not Dowloaded %#",error);
[self downloadFile];
}
else {
NSLog(#"%#",filePath);
[self.downloadRecord removeObjectAtIndex:0];
if (self.downloadRecord.count > 0) {
[self downloadFile];
}
}
}];
There's no official way to set the wallpaper programatically (or add an image/video to the list of wallpapers) from the inside an app. The closest you can achieve would be saving it to the camera role and then letting the user setting it as a wallpaper from there.
However, I believe Apple have used a private API to achieve this in some of their advertisements, however this isn't documented and using it would cause your app to be rejected from the app store approval.

create folder inside nsoperation failed

I use this method inside an NSOperation for check and create a folder:
- (void) checkAndCreateFolderWithPath:(NSString *)path {
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *pathDaControllare = [[self getLibraryPath] stringByAppendingPathComponent:path];
NSError *error = nil;
BOOL isDir;
BOOL exists = [fileManager fileExistsAtPath:pathDaControllare isDirectory:&isDir];
if (exists) {
if (isDir) {
}
}
else {
[fileManager createDirectoryAtPath:pathDaControllare
withIntermediateDirectories:YES
attributes:nil
error:&error];
NSLog(#"%#",error);
}
}
Using NSOperation I get this error:
Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed.
if I don't use NSOperation all work perfectly, this is the nsoperation
- (void) main {
NSString *filePath = [fileDict objectForKey:#"url"];
NSString *urlStr = [NSString stringWithFormat:#"http://www.allmyapp.net/wp-content/iFormulario_Update/%#",filePath];
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[[NSOperationQueue alloc] init]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if (data) {
NSString *folderPath = [filePath stringByReplacingOccurrencesOfString:[filePath lastPathComponent] withString:#""];
[self checkAndCreateFolderWithPath:folderPath];
NSString *pathFile = [[self getLibraryPath] stringByAppendingString:filePath];
[data writeToFile:pathFile atomically:YES];
[self addSkipBackupAttributeToItemAtURL:[NSURL URLWithString:pathFile]];
[[NSNotificationCenter defaultCenter] postNotificationName:#"endFile" object:nil];
[self willChangeValueForKey:#"isFinished"];
[self willChangeValueForKey:#"isExecuting"];
isExecuting = NO;
isFinished = YES;
[self didChangeValueForKey:#"isExecuting"];
[self didChangeValueForKey:#"isFinished"];
}
}];
}
And this the method for create the queue:
for (NSDictionary *dict in fileDaScaricare) {
DownloadOperation *downloadOperation = [[DownloadOperation alloc] initWithDictionary:dict];
[self.operationQueue addOperation:downloadOperation];
}
You can try something like this:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:#"/MyFolder"];
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
[[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];
NSString *docFolderPath = [stringPath stringByAppendingString:[NSString stringWithFormat: #"/%#", self.downloadedFilename]];
[data writeToFile:docFolderPath atomically:YES];
It worked for me, and I am able to download a file in MyFolder. Hope it works for you. Please let me know if it works.

Resources