I am trying to convert NSdata to NSUrl, and I found this method on the internet:
NSString *urlString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
NSURL *url = [[NSURL alloc] initWithString:urlString];
[session sendResourceAtURL:url withName:#"Resource" toPeer:peerID withCompletionHandler:nil];
Seems all right to me, but the app crashes at the second line and gives the error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL initWithString:relativeToURL:]: nil string parameter'
Can't get why...
myData is not UTF-8 encoded.
From the NSString docs:
Returns nil if the initialization fails for some reason (for example
if data does not represent valid data for encoding).
You should always check for this type of condition...
NSString *urlString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
NSURL *url;
if (urlString) {
url = [[NSURL alloc] initWithString:urlString];
} else {
// handle failure
}
Additionally, make sure you're using UTF8 encoding when you create the myData object, or switch from NSUTF8StringEncoding to the correct encoding type.
If dict from [NSKeyedArchiver archivedDataWithRootObject:dict] is NSDictionary class then you must extract the urlString from that dictionary.
NSError* error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSString *urlString = [dictionary valueForKey:#"url"];
change the encoding, say to NSUTF16StringEncoding
your String returns null try these method
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:#".png"];
[fileManager createFileAtPath:fullPath contents:myData attributes:nil];
if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath])
{
NSURL *imageUrl = [NSURL fileURLWithPath:fullPath isDirectory:NO];
}
Related
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];
I am developing an IOS app..Download data From URL and save on local cache..but i am using this code..first time data can stored in Local cache and also read on the text field..but Delete the app on simulator and run the and again store the text file on local cache..file can't be store..Any help or advice is greatly appreciated. thanks in advance.
NSURL *url = [NSURL URLWithString:#"http://webapp.opaxweb.net/books/"];
NSData *data_file = [[NSData alloc]initWithContentsOfURL:url];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]stringByAppendingPathComponent:#"Documents"]];
NSString *filepath = [resourceDocPath stringByAppendingPathComponent:#"gurugranthsahib.txt"];
[data_file writeToFile:filepath atomically:YES];
NSLog(#"%#",filepath);
NSString* content = [NSString stringWithContentsOfFile:filepath
encoding:NSUTF8StringEncoding
error:NULL];
iOS does not allow writing to the app bundle.
Generally data is written to the Documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
Note:
It is much better practice to use a method call that has an error parameter so when there is an error the error can be examined. In this case you could use:
NSError *error;
BOOL status = [string writeToFile:filePath options:NSDataWritingAtomic error:&error];
if (status == NO) {
NSLog(#"error: %#", error)
}
I'm having troubles decrypting pdf files and displaying them with presentViewController after they are encrypted.
When I download the pdf files, they are being encrypted like this:
NSData *pdfData = [[NSFileManager defaultManager] contentsAtPath:filePathDocumetFolder];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documents = [paths objectAtIndex:0];
NSString *docFolder = [NSString stringWithFormat:#"/Documents/%#", documentFilePath];
NSString *filePath = [documents stringByAppendingPathComponent:docFolder];
NSString *pdfName = [NSString stringWithString:filename ];
NSError *error;
NSData *encryptedPdf = [RNEncryptor encryptData:pdfData withSettings:kRNCryptorAES256Settings password:#"A_SECRET_PASSWORD" error:&error];
if(error){
NSLog(#"error: %#", error);
}
NSLog(#"where?? FileTra%#", filePath);
[encryptedPdf writeToFile:[filePath stringByAppendingPathComponent:pdfName] atomically:YES];
I know that this encryption above works, as when I browse the filesystem with iExplorer, I cannot open the files because they are protected.
In my DocumentHandle controller I'm trying to decrypt them so that they can be viewed:
NSDictionary* dict = [command.arguments objectAtIndex:0];
NSString* urlStr = dict[#"url"];
NSURL* url = [NSURL URLWithString:urlStr];
NSString* fileName = [url path];
NSString* path = [NSTemporaryDirectory() stringByAppendingPathComponent: fileName];
NSData *dataEn = [[NSFileManager defaultManager] contentsAtPath:[path stringByAppendingPathComponent:fileName]];
NSLog(#"this to decrypt%#", [path stringByAppendingPathComponent:fileName]);
NSData *decryp = [RNDecryptor decryptData:dataEn withSettings:kRNCryptorAES256Settings password:#"A_SECRET_PASSWORD" error:nil];
[decryp writeToURL:[[NSURL alloc] initFileURLWithPath:path] atomically:YES];
if(decryp){
NSLog(#"decrypted");
}else{
NSLog(#" not decrypted");
}
weakSelf.fileUrl = [[NSURL alloc] initFileURLWithPath:path];
For some reason, the pdf files are not being decrypted and I'm being presented with a blank file even thought I'm receiving NSLog as decrypted :(
Can anyone help me please? thank you
I am having some problems getting my code to work :(
i am trying to download .txt file from the internet and store it in my iphone for further use but it wont work :/
here is my code :
-(void)DownloadFile
{
//declerations
NSString* TheFile;
NSFileManager* FM = [NSFileManager defaultManager];
//downloading file
NSURL *url = [NSURL URLWithString:#"http://www.myfile.com/apple.txt"];
TheFile = [[NSString alloc] initWithContentsOfURL: url
encoding: NSUTF8StringEncoding
error: nil];
//nsstring to nsdata
NSData* data = [TheFile dataUsingEncoding:NSUTF8StringEncoding];
//saving file
[FM createFileAtPath:[DocumentsDir stringByAppendingString:#"/file.txt"] contents:data attributes:nil];
}
DocumentsDir is defined with this function :
-(void)SetDocuments
{
NSArray* doc;
doc = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
DocumentsDir = [doc objectAtIndex:0];
}
Then i use this function assigne the file to a variable:
-(void)SetFile
{
File = [[NSString alloc]
initWithContentsOfFile:[DocumentsDir stringByAppendingString:#"/file.txt"]
encoding:NSUTF8StringEncoding
error:nil];
}
i would appreciate any tips or corrections etc :) thank you for your time.
Change your SetDocuments like this
-(void)SetDocuments{
NSArray* doc;
//doc = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
DocumentsDir = [doc objectAtIndex:0];
}
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