convert url into NSData - ios

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];

Related

How to get url from video reference url

I have a url of video from photo library :-
/var/mobile/Applications/9BC2EBC4-7A71-4C8B-8BFB-D25D01E4CA83/Documents/IMG_5244.MOV
How can i get convert it to NSData I am tried following but nothing worked:
NSString* fileName = movieAsset.defaultRepresentation.filename;
NSURL* fileUrl = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject]URLByAppendingPathComponent:fileName];
NSString *str = [fileUrl path];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
[arrVideoUrls addObject:fileUrl];
Here in your code you have add NSString as an URL and try to convert that NSString URL to NSData, so here first convert that string url to NSURL and then convert it in to NSData like below...
NSString *strVideoURL = #"assets-library://asset/asset.MOV?id=2EBD925F-D275-403E-A6A4-3487134D9B9D&ext=MOV";
NSURL *urlVideo = [NSURL URLWithString:strVideoURL];
NSData *videoData = [NSData dataWithContentsOfURL:urlvideo]];

How to store JSON data in a 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

Saving JSON file to iPhone

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];

NSFileManager Not Saving

I've been trying to use NSFileManager to cache images to the Cache directory of my sandboxed app. Unfortunately, my code doesn't seem to work.
- (BOOL)saveImageToCacheFolder
{
NSFileManager *filemgr = [NSFileManager defaultManager];
NSString *cachePath = [[[filemgr URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] lastObject] absoluteString];
NSString *fullpath = [cachePath stringByAppendingPathComponent:#"test.jpg"];
NSURL *imageURL = [FlickrFetcher urlForPhoto:self.photoData format:FlickrPhotoFormatLarge];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
BOOL success = false;
if (imageData != nil) {
success = [imageData writeToURL:[NSURL URLWithString:fullpath] atomically:true];
if (!success) NSLog(#"Did Not Managed to save the image");
}
return success;
}
Here is what I am trying to do. First, get the default NSFileManager. Second, get the relative path to the cache directory of my app. Third, append the name of my file (here i just wrote test for now). Fourth, convert my image to NSData. Fourth, write the NSData object to the specified path.
edit: added if statement for checking if the imageData is nil
Try this:
NSArray *myPathList = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [myPathList objectAtIndex:0];
NSString *fullpath = [cachePath stringByAppendingPathComponent:#"test.jpg"];
NSURL *imageURL = [FlickrFetcher urlForPhoto:self.photoData format:FlickrPhotoFormatLarge];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
if (imageData != nil) {
success = [imageData writeToURL:[NSURL fileURLWithPath:fullpath] atomically:YES];
if (!success) NSLog(#"Did Not Managed to save the image");
}

resource file is not found when using iPhone simulator

I have the following code. word.txt is in "Supporting Files":
NSString *filePath = [[NSBundle mainBundle] resourcePath];
filePath = [filePath stringByAppendingPathComponent:#"words.txt"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
When I run using the simulator, data is not read properly but if I use the actual device, it works fine.
What is the problem?
This is how I do it and it seems to work for me:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"words" ofType:#"txt"];
NSData *data = [NSData dataWithContentsOfFile:filePath];
if (data) {
NSLog(#"DATA:%#",data);
}
And to set it to a string:
NSString* string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"WORDS:%#",string);

Resources