How to vary the contents in URL in iOS? [closed] - iphone

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I am having a URL in which it contains images and audio files. I am downloading the images and audio files to document directory by using the below code:
// urlsArray contains the list of images and audio urls
for(int i= 0 ;i<[urlsArrray count]; i++)
{
NSString *urlString = [urlsArrray objectAtIndex:i];
NSString *escapedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:escapedUrlString];
NSData *fileData=[NSData dataWithContentsOfURL:url];
NSString *urlstring1 = [url absoluteString];
NSArray *parts = [urlstring1 componentsSeparatedByString:#"/"];
NSString *fileName = [parts objectAtIndex:[parts count]-1];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:fileName];
[fileManager createFileAtPath:savedImagePath contents:fileData attributes:nil];
NSLog(#"files Stored Path is %#",savedImagePath);
Now I want to seperate the images and audio files. I want to download images to document directory and audio files to cache directory.

Just add following code to recognize the file whether it is image or audio file
CFStringRef fileExtension = (CFStringRef) [file pathExtension];
CFStringRef fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);
if (UTTypeConformsTo(fileUTI, kUTTypeImage)) NSLog(#"It's an image");
else if (UTTypeConformsTo(fileUTI, kUTTypeMovie)) NSLog(#"It's a movie");
else if (UTTypeConformsTo(fileUTI, kUTTypeText)) NSLog(#"It's text");
else NSLog(#"It's audio");

OK if you separate from your array then do as below:
imagelist = [[NSMutableArray alloc]init];
videolist = [[NSMutableArray alloc]init];
for(int i = 0;i<urlsArrray.count;i++)
{
id arrayElement = [fileArray objectAtIndex:i];
if([arrayElement rangeOfString:#".mp3" ].location !=NSNotFound)
{
[videolist addObject:arrayElement];
NSLog(#"videolist..%#",videolist);
}
else([arrayElement rangeOfString:#".png"].location !=NSNotFound)
{
[imagelist addObject:arrayElement];
NSLog(#"imagelist..%#",imagelist);
}
}

Related

AVAudioPlayer play from buffer

I want to stream audio file from google drive, the only method from google drive sdk from which I can track what is downloaded is [fetcher setReceivedDataBlock:^(NSData *dataReceivedSoFar), so I implemented something like this, but I am not so sure if this is a good solution so I am asking an advice from you guys.
Ok, since I can only get dataReceivedSoFar, I am deleting the already downloaded data from it, and then appending the new data to saved data, and start playing with AVAudioPlayer when the data length is greater than 100 000 bytes.
Please tell me if this is a good solution and if you have some advice regarding it.
Code:
GTMHTTPFetcher *fetcher =
[[self driveService].fetcherService fetcherWithURLString:song.filePath];
NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [myPathList objectAtIndex:0];
NSString *songPath = [[NSString alloc] initWithString: [cachesDir stringByAppendingPathComponent:[NSString stringWithFormat:#"Song.%#", [song.name pathExtension]]]];
[fetcher setReceivedDataBlock:^(NSData *dataReceivedSoFar) {
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
if (![filemgr fileExistsAtPath: songPath ] == YES)
[filemgr createFileAtPath:songPath contents:nil attributes:nil];
NSData *currentData = [NSData dataWithContentsOfFile:songPath];
NSLog(#"LENGTH: %d", currentData.length);
NSMutableData *mutableData = [NSMutableData dataWithData:dataReceivedSoFar];
if (currentData.length > 0) {
[mutableData replaceBytesInRange:NSMakeRange(0, [currentData length]) withBytes:NULL length:0];
}
NSFileHandle *handle = [NSFileHandle fileHandleForUpdatingAtPath:songPath];
[handle seekToEndOfFile];
[handle writeData:mutableData];
//[handle synchronizeFile];
[handle closeFile];
if (!self.audioPlayer.playing && dataReceivedSoFar.length > 100000)
{
NSURL *URL = [NSURL fileURLWithPath:songPath];
self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:URL error:nil];
[self.audioPlayer play];
NSLog(#"Audio player started playing");
}

When we open pdf in iPhone then how to save this pdf in iphone

I am very new to iOS. I create PDF and load this PDF on UIWebView
now this time I want to save or download this PDF in iPhone when we tapped download button then all exits PDF supporter show like as open ibook ,open in chrome. This type of option show but when we tap any one then my application closed.
-(void)show_Button
{
NSArray *docDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDirectory = [docDirectories objectAtIndex:0];
NSString *filePAth = [docDirectory stringByAppendingPathComponent:#"myPDF.pdf"];
NSLog(#"filePath = %#", filePAth);
NSURL *url2 = [NSURL fileURLWithPath:filePAth];
NSLog(#"url2 = %#", url2);
UIDocumentInteractionController *docContr = [UIDocumentInteractionController
interactionControllerWithURL:url2];
docContr.delegate=self;
[docContr presentOpenInMenuFromRect:CGRectZero inView:self.view animated:YES];
}
so how to save or download this pdf in Iphone please solve this problem....
I believe you can simple use the belo two line:
NSData *myFile = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"your_url"]];
[myFile writeToFile:[NSString stringWithFormat:#"%#/%#", [[NSBundle mainBundle] resourcePath], #"yourfilename.pdf"] atomically:YES];
I hope this it will help you,
Saving the pdf into app
NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: path]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"pdfname.pdf"];
NSError *writeError = nil;
[imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];
if (writeError) {
NSLog(#"Error writing file: %#", writeError); }
Getting the pdf from the NSDocument Directory
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:&error];
for(int i=0;i<[filePathsArray count];i++)
{
NSString *strFilePath = [filePathsArray objectAtIndex:i];
if ([[strFilePath pathExtension] isEqualToString:#"pdf"])
{
NSString *pdfPath = [[stringPath stringByAppendingFormat:#"/"] stringByAppendingFormat:strFilePath];
NSData *data = [NSData dataWithContentsOfFile:pdfPath];
if(data)
{
UIImage *image = [UIImage imageWithData:data];
[arrayOfImages addObject:image];
}
}
}

How to use ogg.framwork in xcode to play audio from url or data

From couple of days I was searching of how to play ogg on iPhone. But not successful. I found this post which points towards precompiled-ogg-vorbis-libraries-for-ios, but I don't know how to use this framework or libraries. I am new in coding. I also found this post
but it plays ogg audio from bundle. I want to play from a given url, like wikipedia audios. any help will be great. Thanks
UPDATE:
I found another library or file which can be use in iOS but, still I don't know how to use in Xcode. Ogg Vorbis I audio decoder by Sean Barrett. Any idea how to use this.
UPDATE 2:
Just tried to use it something like this, but output file have no sound. Any idea where I am going wrong.
NSString *file = #"http://upload.wikimedia.org/wikipedia/commons/b/b2/En-us-Pakistan.ogg";
NSURL *fileURL = [NSURL URLWithString:file];
NSData * data = [NSData dataWithContentsOfURL:fileURL];
unsigned char* array = (unsigned char*) [data bytes];
int len = [data length];
if (data != nil) {
NSLog(#"\nis not nil");
//NSString *readdata = [[NSString alloc] initWithContentsOfURL:(NSData *)data ];
stb_vorbis* Stream = stb_vorbis_open_memory(array, len, NULL, NULL);
if (Stream)
{
stb_vorbis_close(Stream);
//return true;
}
else
{
//return false;
}
}
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
NSData *ddata = [NSData dataWithBytes:byteData length:len];
if (ddata == nil) {
NSLog(#"data nil");
}
else{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"wikiaudio"];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder if it doesn't already exist
NSString * filename = [#"hello" stringByAppendingString:#".mp3"];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", dataPath,filename];
[ddata writeToFile:filePath atomically:YES];
NSLog(#"filepath %#", filePath);
}

how to get image from document directry to uiview in iphone? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
hi friend i am saving image on document directry like this
in document directry the image is asaving like saveimage0.png,saveimage1.png...etc like this image is enter in document i create int variable for increment count with image num=0;
insert is working proper but how to get multiple image from document folder in loadimage menthod is right or wrong i want tkae image and save in array and display on view
int num=0;
-(void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *mediaType = [info
objectForKey:UIImagePickerControllerMediaType];
[self dismissModalViewControllerAnimated:YES];
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
UIImage *image = [info
objectForKey:UIImagePickerControllerOriginalImage];
imageView.image = image;
UIImage *image1 =imageView.image;
NSData *myData = [UIImagePNGRepresentation(image1) retain];
imagedata = myData;
if (newMedia)
UIImageWriteToSavedPhotosAlbum(image,
self,
#selector(image:finishedSavingWithError:contextInfo:),
nil);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"saveimage%d.png",num]];
num += 1; // for next t
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])
{
// Code here to support video if enabled
}
}
and i am fetching image from document directry same as
int value;
- (UIImage*)loadImage
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// NSString* path = [documentsDirectory stringByAppendingPathComponent:
//[NSString stringWithString: #"test.png"] ];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"savedImage-",#"%#-%d.png", value]];
value += 1;
UIImage* image = [UIImage imageWithContentsOfFile:path];
return image;
}
Answer is within your question.
You are saving image using:
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"saveimage%d.png",num]];
The format is : saveimage0.png
And you are retrieving like:
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"savedImage-",#"%#-%d.png", value]];
The format is: savedImage-aValue-aValue.png.
Change it to:
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"savedimage%d.png", value]];

covert sqlite database in to csv format? and then mail this csv file in iPhone Objective C [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to share all the data i have stored using sqlite database between two devices to reuse the data by dumping in another device
I want to import a sqlite Database and save it as a CSV file and then mail this file via email.
can i import sqlite in to csv format in iphone app programmatically to attach in mail composer
i used following functio to get the data base file
+(NSString*)getSqliteDBFile
{
NSString *docsDirectoryPath;
NSArray *dirPaths;
NSString *databasePath;
NSFileManager *fileManager = [NSFileManager defaultManager];
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDirectoryPath = [dirPaths objectAtIndex:0];
NSLog(#"path :%#", docsDirectoryPath);
// Build the path to the database file
databasePath = [[NSString alloc] initWithString: [docsDirectoryPath stringByAppendingPathComponent: #"LeadGenDB.sqlite"]];
NSLog(#"path :%#", databasePath);
return databasePath;
}
Now I nees to convert sqlite file to csv file
you can not convert direct sqlite to csv. First you get your all database data and write into csv file.use below example for create csv and send it.
NSString *csvString =#"1,2 , 3 , 4, 5 ,6 , 7";
for(int i=0;i<rangeData.count ;i++)
{
NSArray *temp = [di timeCalculation:[[rangeData objectAtIndex:i] objectForKey:#""] :[[rangeData objectAtIndex:i] objectForKey:#""]];
NSString *strTemp =[NSString stringWithFormat:#"%#,%#,%#,%#,%#,%#,%#",
[NSString stringWithFormat:#"%#",[simpleDate stringFromDate:[[NSDate alloc]initWithTimeIntervalSince1970:[[[rangeData objectAtIndex:i] objectForKey:#""] floatValue]]]],
[NSString stringWithFormat:#"%#",[shrotDate stringFromDate:[[NSDate alloc]initWithTimeIntervalSince1970:[[[rangeData objectAtIndex:i] objectForKey:#""] floatValue]]]],
[NSString stringWithFormat:#"%#",[shrotDate stringFromDate:[[NSDate alloc]initWithTimeIntervalSince1970:[[[rangeData objectAtIndex:i] objectForKey:#""] floatValue]]]],
[NSString stringWithFormat:#"%#",[shrotDate stringFromDate:[[NSDate alloc]initWithTimeIntervalSince1970:[[[rangeData objectAtIndex:i] objectForKey:#""] floatValue]]]],
[NSString stringWithFormat:#"%#",[shrotDate stringFromDate:[[NSDate alloc]initWithTimeIntervalSince1970:[[[rangeData objectAtIndex:i] objectForKey:#""] floatValue]]]],
[NSString stringWithFormat:#"%#",[[temp objectAtIndex:0] stringByReplacingOccurrencesOfString:#": " withString:#""]] ,
[NSString stringWithFormat:#"%#",[[temp objectAtIndex:1] stringByReplacingOccurrencesOfString:#" : " withString:#""]]];
csvString = [NSString stringWithFormat:#"%# \n %#",csvString,strTemp];
}
//create instance of NSFileManager
NSFileManager *fileManager = [NSFileManager defaultManager];
//create an array and store result of our search for the documents directory in it
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//create NSString object, that holds our exact path to the documents directory
NSString *documentsDirectory = [paths objectAtIndex:0];
NSLog(#"Document Dir: %#",documentsDirectory);
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.csv", #"userdata"]]; //add our file to the path
[fileManager createFileAtPath:fullPath contents:[csvString dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
NSData *csvData =[NSData dataWithContentsOfFile:fullPath];
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
controller.mailComposeDelegate = self;
[controller setToRecipients:[NSArray arrayWithObject:#""]];
[controller setSubject:#"CSV Export"];
[controller setMessageBody:#"" isHTML:NO];
[controller addAttachmentData:csvData mimeType:#"text/csv" fileName:#"userdata.csv"];
[self presentModalViewController:controller animated:YES];
[controller release];