objective c - convert mpmediaitem to ogg vorbis - objective-c

i found (customizing a method i found) a way to convert a MpMediaItem and to obtain a mp3 file. Probably it's not the best way but it's working.
Is there a way to obtain an *.ogg file instead of *.mp3 ? What would be the proper approach?
This is the method i use to get the *.mp3 file:
-(void)exportMP3:(NSURL*)url toFileUrl:(NSString*)fileURL
{
AVURLAsset *asset=[[AVURLAsset alloc] initWithURL:url options:nil];
AVAssetReader *reader=[[AVAssetReader alloc] initWithAsset:asset error:nil];
NSMutableArray *myOutputs =[[NSMutableArray alloc] init];
for(id track in [asset tracks])
{
AVAssetReaderTrackOutput *output=[AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:track outputSettings:nil];
[myOutputs addObject:output];
[reader addOutput:output];
}
[reader startReading];
NSFileHandle *fileHandle ;
NSFileManager *fm=[NSFileManager defaultManager];
if(![fm fileExistsAtPath:fileURL])
{
[fm createFileAtPath:fileURL contents:[[NSData alloc] init] attributes:nil];
}else{
NSURL *url = [NSURL URLWithString:fileURL];
[fm removeItemAtURL:url error:nil];
[fm createFileAtPath:fileURL contents:[[NSData alloc] init] attributes:nil];
}
fileHandle=[NSFileHandle fileHandleForWritingAtPath:fileURL];
[fileHandle seekToEndOfFile];
AVAssetReaderOutput *output=[myOutputs objectAtIndex:0];
int totalBuff=0;
int test = 1;
while(test == 1)
{
CMSampleBufferRef ref=[output copyNextSampleBuffer];
if(ref==NULL)
test = 0;
if(ref==NULL)
break;
//copy data to file
//read next one
AudioBufferList audioBufferList;
NSMutableData *data;
CMBlockBufferRef blockBuffer;
CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(ref, NULL, &audioBufferList, sizeof(audioBufferList), NULL, NULL, 0, &blockBuffer);
for( int y=0; y<audioBufferList.mNumberBuffers; y++ )
{
AudioBuffer audioBuffer = audioBufferList.mBuffers[y];
void *frame = audioBuffer.mData;
data = [[NSMutableData alloc] initWithBytes:frame length:audioBuffer.mDataByteSize];
}
totalBuff++;
NSLog(#"\n%d\n",totalBuff);
int time = [self.mediaPlayer durationOfCurrentItem];
if (totalBuff * 2 <= time + 1)
[fileHandle writeData:data];
}
[fileHandle closeFile];
}

You can use libvorbis to encode PCM data to Vorbis.

Related

Check auto-renewable subscription expire date from validate receipt

I am calling receipt validation method in app delegate to check the renewable process. Its working fine in development mode but after releasing from app store its always returning yes, even though user have not purchase the product. Please Suggest what wrong I am doing. In sandbox mode its working fine but after release I found the issue that its always returning true. For validating receipt I am using below code
// Validate the receipt
+(BOOL ) getStoreReceipt:(BOOL)sandbox andTrasaction:(SKPaymentTransaction *)tractaion{
NSArray *objects;
NSArray *keys;
NSDictionary *dictionary;
BOOL gotreceipt = false;
#try {
NSURL *receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];
if ([[NSFileManager defaultManager] fileExistsAtPath:[receiptUrl path]]) {
NSData *receiptData = [NSData dataWithContentsOfURL:receiptUrl];
NSString *receiptString = [self base64forData:receiptData];
NSLog(#"receiptString Value---->= %#",receiptString);
NSString *encReceipt = [receiptData base64EncodedStringWithOptions:0];
NSLog(#"receiptString Value ======>= %#",encReceipt);
if (receiptString != nil) {
NSString *strSharedSecrect = #"MY_Secrect_Key";
objects = [[NSArray alloc] initWithObjects:receiptString,strSharedSecrect, nil];
keys = [[NSArray alloc] initWithObjects:#"receipt-data",#"password", nil];
dictionary = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
NSString *postData = [self getJsonStringFromDictionary:dictionary];
NSLog(#"postData Value---->= %#",receiptString);
NSString *urlSting = #"https://buy.itunes.apple.com/verifyReceipt";
// if (sandbox) urlSting = #"https://sandbox.itunes.apple.com/verifyReceipt";
dictionary = [self getJsonDictionaryWithPostFromUrlString:urlSting andDataString:postData];
NSLog(#"dictionary Value for receipt---->= %#",dictionary);
if ([dictionary objectForKey:#"status"] != nil) {
if ([[dictionary objectForKey:#"status"] intValue] == 0) {
gotreceipt = true;
}
}
}
}//623065
} #catch (NSException * e) {
gotreceipt = false;
return NO;
NSLog(#"NSException---->= %#",e);
}
if (!gotreceipt) {
NSLog(#"Not gotreceipt---->=");
objects = [[NSArray alloc] initWithObjects:#"-1", nil];
keys = [[NSArray alloc] initWithObjects:#"status", nil];
dictionary = [[NSDictionary alloc] initWithObjects:objects forKeys:keys];
return NO;
}else{
BOOL isPurchased = [self PurchasedSubscriptionStatues:dictionary];
return isPurchased;
}
return NO;
}
Checking if pending for renewable is there or not...
+(BOOL)PurchasedSubscriptionStatues:(NSDictionary *)transactionReceipt
{
if ([[transactionReceipt allKeys] containsObject:#"pending_renewal_info"]) {
NSArray *arrData = [transactionReceipt objectForKey:#"pending_renewal_info"];
NSDictionary *dicPendinRenew = [arrData objectAtIndex:0];
if ([[dicPendinRenew allKeys] containsObject:#"expiration_intent"] || [[dicPendinRenew objectForKey:#"auto_renew_status"] integerValue]==0) {
return NO;
}else if ([[dicPendinRenew objectForKey:#"auto_renew_status"] integerValue]==1) {
return YES;
}else{
return NO;
}
}else{
return YES;
}
return NO;
}
Convert String To Dictionary
+(NSString *)getJsonStringFromDictionary:(NSDictionary *)dicVal
{
NSError *error = nil;
NSData *postData = [NSJSONSerialization dataWithJSONObject:dicVal options:NSJSONWritingPrettyPrinted error:&error];
NSString *postString = #"";
if (! postData) {
NSLog(#"Got an error: %#", error);
return nil;
}
else { postString = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
return postString;
}
}
Convert Dictionary to string
+(NSDictionary *) getJsonDictionaryWithPostFromUrlString:(NSString *)urlString andDataString:(NSString *)dataString {
NSString *jsonString = [self getStringWithPostFromUrlString:urlString andDataString:dataString];
NSLog(#"getJsonDictionaryWithPostFromUrlString-->%#", jsonString); // see what the response looks like
return [self getDictionaryFromJsonString:jsonString];
}
+ (NSDictionary *) getDictionaryFromJsonString:(NSString *)jsonstring {
NSError *jsonError;
NSDictionary *dictionary = (NSDictionary *) [NSJSONSerialization JSONObjectWithData:[jsonstring dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&jsonError];
if (jsonError) {
dictionary = [[NSDictionary alloc] init];
}
return dictionary;
}
//Request for post method to get the recipt
+ (NSString *) getStringWithPostFromUrlString:(NSString *)urlString andDataString:(NSString *)dataString {
NSString *s = #"";
#try {
NSData *postdata = [dataString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postlength = [NSString stringWithFormat:#"%d", [postdata length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setTimeoutInterval:60];
[request setHTTPMethod:#"POST"];
[request setValue:postlength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postdata];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if (data != nil) {
s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
}
#catch (NSException *exception) {
s = #"";
}
return s;
}
// from https://stackoverflow.com/questions/2197362/converting-nsdata-to-base64
+ (NSString*)base64forData:(NSData*)theData {
const uint8_t* input = (const uint8_t*)[theData bytes];
NSInteger length = [theData length];
static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t* output = (uint8_t*)data.mutableBytes;
NSInteger i;
for (i=0; i < length; i += 3) {
NSInteger value = 0;
NSInteger j;
for (j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
NSInteger theIndex = (i / 3) * 4;
output[theIndex + 0] = table[(value >> 18) & 0x3F];
output[theIndex + 1] = table[(value >> 12) & 0x3F];
output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}
------------------------------------------------------------------------
I think your PurchasedSubscriptionStatues method has an error: if the receipt does not contain pending_renewal_info key, it returns YES. Try creating a new sandbox user and see if the receipt contains this key, if not - then this method should return NO in such case.
Also, you can try using some library that can manage InApp purchases, like RMStore, to ease on the receipt verification.

Memory leak using ARC in NSData framework

i can't figure out one memory leak. I will add screen shot with code and marked line where this happens.
Maybe some could help me and take a look.
Thanks.
- (AVAudioPlayer*)getSpeachSoundObject{
NSString *objectIDString = [NSString stringWithFormat:#"%i", jmObject.objectID];
NSString * __weak textPlaySource = [DataController getMediaUrlStringForObjectID:objectIDString parentType:PARENT_TYPE_ITEM_AUDIO];
NSError * error = nil ;
if (textPlaySource) {
//NSURL *soundURL = [[NSURL alloc] initFileURLWithPath:textPlaySource];//[NSURL fileURLWithPath:textPlaySource];
NSData * data = [NSData dataWithContentsOfFile:textPlaySource options:NSDataReadingMapped error:&error ] ;
textPlaySource = nil;
NSError *error;
//speechSound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:&error];
AVAudioPlayer *lspeechSound = data ? [[AVAudioPlayer alloc] initWithData:data error:&error ] : nil ;
data = nil;
if (error) {
WLog([NSString stringWithFormat:#"Error creating sound file:%#", error]);
}
return lspeechSound;
//soundURL = nil;
}
return nil;
}

iOS NSMutableData *data = [[NSMutableData alloc] init]; crashes

I m using below mentioned line in a function
NSMutableData *data = [[NSMutableData alloc] init];
And I m calling this function a no of time (e.g. 100 times). So my problem is that initially for about 60 times or more it is working properly but after that it gives me "BAD_EXC_ACCESS"
Function is given below
+ (NSString *) recvToFile:(NSString *)_fileName {
#try {
int _sz = [self recvNumber:4];
uint8_t t[_sz];
NSMutableData *data = [[NSMutableData alloc] init];
NSMutableData *fileData = [[NSMutableData alloc] init];
long _pos = 0;
NSString *_fullPath = _fileName;
while (_sz > _pos) {
long _c = [m_sin read:t maxLength:_sz];
_pos += _c;
data = [NSData dataWithBytes:t length:_c];
if([Misc checkFileExists:_fileName]==nil)
[[NSFileManager defaultManager] createFileAtPath:_fullPath contents:nil attributes:nil];
[fileData appendData:data];
}
[fileData writeToFile:_fullPath atomically:YES];
NSDictionary *attr = [[NSFileManager defaultManager] attributesOfItemAtPath:_fullPath error:nil];
long long length = [[attr valueForKey:#"NSFileSize"] intValue];
if (length >= _sz)
return (_fullPath);
}
#catch (NSException * e) {
}
return (nil);
}
And I m calling this function every time i receive a file. I want to save file from bytes
You should not initialize data here:
NSMutableData *data = [[NSMutableData alloc] init];
just initialize the variable to nil;
NSMutableData* data = nil;
Try adding data like this to nsmutabledata
[data appendBytes:t length:_c];

Saving images to a directory

Hi I want to save an image to a directory, I pass the NSData and do what I think will save the file in a directory I create but the problem is that it doesn't save. This is what I have so far. Why doesn't the initWithContentsOfURL:encoding:error: work, it returns null but the other method I used works? The main problem is WRITETOURL which returns a 0 which i think means that the information wasn't stored properly, any tips?
NSFileManager *fm = [[NSFileManager alloc] init];
NSArray * directoryPaths = [fm URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
NSLog(#"%#", directoryPaths);
NSURL* dirPath = nil;
dirPath = [[directoryPaths objectAtIndex:0] URLByAppendingPathComponent:[NSString stringWithFormat:#"photos.jpeg"]];
NSError* theError = nil;
[fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES attributes:nil error:&theError];
UIImage* photoToStore = [UIImage imageWithData:photoToSave];
NSString *pathContainingPhoto = [[NSString alloc] initWithFormat:#"%#.jpeg", UIImageJPEGRepresentation(photoToStore, 1.0)];
NSError *error = nil;
BOOL OK = [pathContainingPhoto writeToURL:dirPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(#"OK = %d", OK); //Returns 0
NSLog(#"%#", dirPath);
//WHY DOESNT THIS VERSION WORK?
// NSString *pathToFile = [[NSString alloc] initWithContentsOfURL:dirPath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", pathToFile);
NSString* pathToFile = [NSString stringWithContentsOfURL:dirPath encoding:nil error:nil];
NSArray *dirContents = [fm contentsOfDirectoryAtPath:pathToFile error:nil];
NSLog(#"%#", dirContents);
Do like this and int count in .h file and set its intial value count = 0; in viewDidLoad:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:[NSString stringWithFormat:#"Image_%d.png",count];
error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath]) // removing item it already exuts
{
[[NSFileManager defaultManager] removeItemAtPath:stringPath error:&error];
}
if(photoToSave) // nsdata of image that u have
{
[photoToSave writeToFile:stringPath atomically:YES];
}
count++; // maintaining count of images

Create csv file from array of data in iOS

I want to write data from sql file to csv file. I have collected all data from sql file in an array and using for loop i am appending and writing data to .csv file. but it seems that it shows data in one line only it does not go to new line to create new row.
I have used this for reference.
This is my code :
-(NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:#"myfile.csv"];
}
- (IBAction)saveAsFileAction:(id)sender {
if (![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
[[NSFileManager defaultManager] createFileAtPath: [self dataFilePath] contents:nil attributes:nil];
NSLog(#"Route creato");
}
NSString *writeString;
for (int i=0; i<[dataArray count]; i++) {
writeString = [NSString stringWithFormat:#"%#, %#, %#, %#, %0.2f,",[[dataArray objectAtIndex:i]dates],[[dataArray objectAtIndex:i] time],[[dataArray objectAtIndex:i] category],[[dataArray objectAtIndex:i]place],[[dataArray objectAtIndex:i] amount]];
NSLog(#"writeString :%#",writeString);
NSFileHandle *handle;
handle = [NSFileHandle fileHandleForWritingAtPath: [self dataFilePath] ];
//say to handle where's the file fo write
[handle truncateFileAtOffset:[handle seekToEndOfFile]];
//position handle cursor to the end of file
[handle writeData:[writeString dataUsingEncoding:NSUTF8StringEncoding]];
}
}
This only writes one line because you rewrite the file every time you go through your loop. It is best to not writeData on the file until the loop has completed. I would also use an NSMutableString like this:
- (IBAction)saveAsFileAction:(id)sender {
if (![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
[[NSFileManager defaultManager] createFileAtPath: [self dataFilePath] contents:nil attributes:nil];
NSLog(#"Route creato");
}
NSMutableString *writeString = [NSMutableString stringWithCapacity:0]; //don't worry about the capacity, it will expand as necessary
for (int i=0; i<[dataArray count]; i++) {
writeString = [writeString appendString:[NSString stringWithFormat:#"%#, %#, %#, %#, %0.2f, \n",[[dataArray objectAtIndex:i]dates],[[dataArray objectAtIndex:i] time],[[dataArray objectAtIndex:i] category],[[dataArray objectAtIndex:i]place],[[dataArray objectAtIndex:i] amount]]]; //the \n will put a newline in
}
}
//Moved this stuff out of the loop so that you write the complete string once and only once.
NSLog(#"writeString :%#",writeString);
NSFileHandle *handle;
handle = [NSFileHandle fileHandleForWritingAtPath: [self dataFilePath] ];
//say to handle where's the file fo write
[handle truncateFileAtOffset:[handle seekToEndOfFile]];
//position handle cursor to the end of file
[handle writeData:[writeString dataUsingEncoding:NSUTF8StringEncoding]];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *root = [documentsDir stringByAppendingPathComponent:#"customers.csv"];
NSString *temp;
temp = [NSString stringWithFormat:#"%#", [arrCustomersName objectAtIndex:0]];
for (int i = 1; i < [arrCustomersName count]; i++) {
temp = [temp stringByAppendingFormat:#", %#", [arrCustomersName objectAtIndex:i]];
}
[temp writeToFile:root atomically:YES encoding:NSUTF8StringEncoding error:NULL];
Try this it's working for me ,
If any one want to create .csv file in swift 3
// MARK: CSV file creating
func creatCSV() -> Void {
let fileName = "Tasks.csv"
let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName)
var csvText = "Date,Task Name,Time Started,Time Ended\n"
for task in taskArr {
let newLine = "\(task.date),\(task.name),\(task.startTime),\(task.endTime)\n"
csvText.append(newLine)
}
do {
try csvText.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("Failed to create file")
print("\(error)")
}
print(path ?? "not found")
}
}
For more details you can refer Detail Answer
Hopes this will help to some one .
// For CSV File :
NSMutableString *stringToWrite = [[NSMutableString alloc] init];
[stringToWrite appendString:[NSString stringWithFormat:#"First Name,Last Name,Full Name,Phone Number, Email,Job, organizationName,Note\n\n"]];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
for(int i = 0 ;i<[Contact count];i++) {
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[[Contact objectAtIndex:i] valueForKey:#"firstName"] ]];
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[[Contact objectAtIndex:i] valueForKey:#"lastName"] ]];
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[[Contact valueForKey:#"userName"] objectAtIndex:i]]];
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[[Contact objectAtIndex:i] valueForKey:#"phoneNumber"] ]];
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[[Contact objectAtIndex:i] valueForKey:#"emailAddress"] ]];
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[[Contact objectAtIndex:i] valueForKey:#"jobTitle"] ]];
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[[Contact objectAtIndex:i] valueForKey:#"organizationName"] ]];
[stringToWrite appendString:[NSString stringWithFormat:#"%#\n",[[Contact objectAtIndex:i] valueForKey:#"note"] ]];
}
dispatch_async(dispatch_get_main_queue(), ^(void) {
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentDirectory=[paths objectAtIndex:0];
NSString *strBackupFileLocation = [NSString stringWithFormat:#"%#/%#", documentDirectory,#"ContactList.csv"];
[stringToWrite writeToFile:strBackupFileLocation atomically:YES encoding:NSUTF8StringEncoding error:nil];
});
});