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.
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 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);
}
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];
I want to download or save youtube video in document directory and then play that video using MPMoviePlayerViewController. But I don't know why my code is not working.
I'm using this below code :
prgrma mark- download Or save
-(IBAction)onclick_download:(id)sender
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"Downloading Started");
NSString *urlToDownload = #"youtubeurl";
NSURL *url = [NSURL URLWithString:urlToDownload];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"thefile.mp4"];
//saving is done on main thread
dispatch_async(dispatch_get_main_queue(), ^{
[urlData writeToFile:filePath atomically:YES];
NSLog(#"File Saved !");
});
}
});
}
pragma mark- Play video from document directory
-(IBAction)onclick_playvideolocally:(id)sender
{
[self playvideolocally];
}
-(void)playvideolocally
{
NSURL *videoUrl;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];
NSLog(#"files array %#", filePathsArray);
NSString *fullpath;
for ( NSString *apath in filePathsArray )
{
fullpath = [documentsDirectory stringByAppendingPathComponent:apath];
videoUrl =[NSURL fileURLWithPath:fullpath];
}
MPMoviePlayerViewController *videoPlayerView = [[MPMoviePlayerViewController alloc] initWithContentURL:videoUrl];
[self presentMoviePlayerViewControllerAnimated:videoPlayerView];
[videoPlayerView.moviePlayer play];
}
As your link you provided in url is for youtube so it is not downloaded or saved in local
Use this for youtube
Ive used classes from this project: https://github.com/larcus94/LBYouTubeView It works fine for me. I can download youtube videos.
LBYouTubeExtractor *extractor = [[[LBYouTubeExtractor alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:(#"http://www.youtube.com/watch?v=%#"), self.videoID ]] quality:LBYouTubeVideoQualityLarge] autorelease];
[extractor extractVideoURLWithCompletionBlock:^(NSURL *videoURL, NSError *error) {
if(!error) {
NSLog(#"Did extract video URL using completion block: %#", videoURL);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL: videoURL];
NSString *pathToDocs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filename = [NSString stringWithFormat:(#"video_%#.mp4"), self.videoID ];
[data writeToFile:[pathTODocs stringByAppendingPathComponent:filename] atomically:YES];
NSLog(#"File %# successfully saved", filename);
});
} else {
NSLog(#"Failed extracting video URL using block due to error:%#", error);
}
}];
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;
}