Saving the Response to a file and reading that file in iOS - iphone

Im getting a BSON response from the server.I want to save it to a file and read that file instead of directly reading the response.
This is the method where im getting the response
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
// NSString* path = [[NSBundle mainBundle] pathForResource:#"data"
ofType:#"txt"];
// NSString* content = [NSString stringWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:NULL];
[self readTillEOF];
NSRange range = NSMakeRange(0, [data length] - 3);
NSData *refinedData = [data subdataWithRange:range];
[delegate didRecieveTillEof:refinedData];
}
can anyone please help me with this.
Thanks in advance.

EDIT : Take a look at this how to convert BSON into NSString
Check if u can convert your data into array or dictionary and that can be used for saving in document directory like this.

Related

The operation couldn’t be completed. (Cocoa error 260.)

I'm new on IOS development and i'm working on a pdf application and i need to store a PDF file on a NSData variable, I have the PDF path but i get this message error when i try to put this pdf on the NSData variable using dataWithContentsOfFile her is my simple code :
NSError *error;
NSString *PdfPath = [NSString stringWithFormat:(#"%#"),document.fileURL ];
NSString *newPath = [PdfPath stringByReplacingOccurrencesOfString:#"file://localhost" withString:#""];
NSLog(#"OriginalPdfPath => %#", newPath);
NSData *pdfData = [NSData dataWithContentsOfFile:newPath options:NSDataReadingUncached error:&error];
NB : the pdf path is in this format : /Users/bluesettle/Library/Application%20Support/iPhone%20Simulator/6.0/Applications/BBEF320E-7E2A-49DA-9FCF-9CFB01CC0402/ContractApp.app/Pro.iOS.Table.Views.pdf
thanks for your help
Cocoa error 260 is a NSFileReadNoSuchFileError (as listed in FoundationErrors.h), meaning the file could not be found at the path you specified.
The problem is that your path still contains encoded spaces (%20), because you're basing it on the URL. You can simply do this:
NSData *pdfData = [NSData dataWithContentsOfFile:[document.fileURL path]];
Try to use NSBundle
NSString *newPath = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"pdf"]
Edit:
Than you can use bundleWithPath method, here is an example:
NSString *documentsDir= [NSString stringWithFormat:#"%#/Documents", NSHomeDirectory()];
NSString *newPath= [[NSBundle bundleWithPath:documentsDir] bundlePath];

iOS - how to read entire content of an html resource file into an NSString *?

I want to put the content of my html resource file into an NSString object. Is it possible and advisable to do that? How could it be done?
Possible? - yes
Advisable? - unless it is an extremely large file, why not?
How? - There is already a method to do it for you in NSString - stringWithContentsOfFile:encoding:error:.
See the snippet below:
NSError* error = nil;
NSString *path = [[NSBundle mainBundle] pathForResource: #"foo" ofType: #"html"];
NSString *res = [NSString stringWithContentsOfFile: path encoding:NSUTF8StringEncoding error: &error];

iPhone, NSURLConnection > didReceiveData:(NSData *)data, How to check result data

I use url connection (http).
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSString *filePath; /* .../link.plist */
[data writeToFile:filePath atomically:YES];
}
After connection, I check result file (link.plist)
- (void)checkLinkResult {
NSString *filePath; //link.plist
NSString *result = [[NSString alloc] initWithContentsOfFile:filePath];
}
It works fine.
But I want to check Result String, directly, without making file.
"NSData -> file -> NSString" (now) ====> "NSData -> NSString" (i want)
Help me plz.
It's dependent your data.
If your data is Image
UIIMage * image = [[UIImage alloc] initWithData:Receivedata
If data is string
NSMutableString *string = [[NSMutableString alloc] initwithData:Receivedata encoding:nil]
In didReceiveData write to an NSMutableData object, then in checkLinkResult create a string from the NSMUtableData using the appropriate encoding.
It's actually how it's done in the apple NSConnection tutorial.
Follow the following steps:
Declare a file scope NSMutableData instance.
in your connection:DidRecieveData: callback append "data" to the previously created NSMutableData instance.
In connectionDidFinishLoading: callback use initWithData:encoding: of NSString and pass the NSMutableData instance and NSUTF8StringEncoding as parameters.

How Can I Get Remote FileName on Host When download it via ASIHttpRequest

How Can I Get Remote FileName on Host When download it via ASIHttpRequest??
for example, some url like this:
http://www.filedropper.com/processing/filedownload.php?id=test_22
test_22 is my filename, but original string is #"test_22.gif" , i can not analysis the filename extension from url.
i am trying to get responseString for the real filename when ASIHttpRequest call it delegate method :
- (void)request:(ASIHTTPRequest *)request
didReceiveResponseHeaders:(NSDictionary *)responseHeaders
but i got nothing useful.
any idea?
i hope, you can get file name through the following code..see the link to find file type.after finding append it..
NSString *url = #"http://www.filedropper.com/processing/filedownload.php?id=test_22";
NSArray *parts = [url componentsSeparatedByString:#"="];
NSString *filename = [parts objectAtIndex:[parts count]-1]; // or NSString *filename = [parts lastObject];

Problem writing string to a file ...(iPhone SDK )

I want to grab all URL's accessed in webview and write them to a text file.I don't want to use writeToFile coz in -(BOOL)webView method it would overwrite instead of appending to file. I can create file but all it writes to that file is string I used to create the file using FileManager createFileAtPath with Content ...
Also in the -(BOOL) webView method... when I tried to see if the file is read-only or writable ( isWritableFileAtPath ) it gives read-only.
POSIX Permissions in viewDidLoad -> 511 ...
checked file attributes in terminal going to that location its -rwxrwxrwx
I am new to Stack Overflow don't know how to post code here so using pastebin...http://pastebin.com/Tx7CsXVB
- (void)viewDidLoad {
[super viewDidLoad];
[myBrowser loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.apple.com"]]]; // UIWebView *myBrowser; is an instance variable
NSFileManager *fileMgr=[NSFileManager defaultManager];
NSDictionary* fileAttrs = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:777] forKey:NSFilePosixPermissions]; /*for setting attribute to rwx for all users */
NSDictionary *attribs; // To read attributes after writing something to file
NSString *aPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/file1.txt"];
myBrowser.delegate = self; // UIWebView delegate Self
// if the File Doesn't exist create one
if([fileMgr fileExistsAtPath:aPath])
{
NSLog(#"File Exists at this Location");
}
else
{
NSString *someString = #"This is start of file";
NSData *startString =[someString dataUsingEncoding: NSASCIIStringEncoding];
[fileMgr createFileAtPath:aPath contents:startString attributes: fileAttrs]; // earlier attributes was nil changed to fileAttrs
}
NSLog(#"aPath is %#",aPath);
attribs = [fileMgr attributesOfItemAtPath:aPath error: NULL];
NSLog (#"Created on %#", [attribs objectForKey: NSFileCreationDate]);
NSLog (#"File type %#", [attribs objectForKey: NSFileType]);
NSLog (#"POSIX Permissions %#", [attribs objectForKey: NSFilePosixPermissions]);
}
//UIWebView delegate calls this method every time user touches any embedded URL's in the current WebPage. I want to grab all the URL's accessed and write them to file.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSFileManager *fileManager =[NSFileManager defaultmanager];
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/file1.txt"];
fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
[fileHandle seekToEndOfFile]; // Moved up next to fileHandleForWritingAtPath since the above would place pointer to start of file again so setting handle to seek to End of File
/* section of code to check if the file at that path is writable or not */
if ([fileManager isWritableFileAtPath:path] == YES)
NSLog (#"File is writable");
else
NSLog (#"File is read only");
/* section of code to check if the file at that path is writable or not ENDS*/
NSURL *url = request.URL;
NSString *currenturl = url.absoluteString;
NSString *currentURL = [NSString stringWithFormat:#"%#\n",currenturl];
NSString *str =[NSString stringWithFormat:#"%#",currentURL];/* has already been set up */
[fileHandle writeData:[str dataUsingEncoding:NSUTF8StringEncoding]];
// testing if string has been written to file by reading it...
NSData *dataBuffer = [fileMgr contentsAtPath:path];
NSString *some;
some = [[NSString alloc] initWithData:dataBuffer encoding:NSASCIIStringEncoding];
NSLog(#"SOme String is: %#",some);
[fileHandle closeFile];
}
I think your issue may be that you're testing Documents/file1.txt and not /Documents/file1.txt
The leading '/' is important
[edit]
May I make a suggestion? Distill this down to what works first and then figure out what makes it fail?
I would recommend using the following form and continuing from there:
if ([fileManager isWritableFileAtPath: #"/Documents/file1.txt"] == YES)
NSLog (#"File is writable");
else
NSLog (#"File is read only");
[/edit]