I'm trying to send a string via ftp using the code below but I'm getting an error:
{
//miscellaneous lines of code.....
//Convert contents of shopping cart into a property list
[Cart serializeCart];
//now need to transport the propertyList to the webserver
//first step is get the serialized propertylist from the documents folder
NSString *pathToSerializedCart = [rootPath stringByAppendingPathComponent:#"serializedCart.plist"];
NSString *shoppingCartString;
if (![fileManager fileExistsAtPath:pathToSerializedCart])
{
NSLog(#"ERROR:\nCouldnt find serialized cart in documents folder.");
}
else
{
NSData *serializedData = [NSData dataWithContentsOfFile:pathToSerializedCart];
shoppingCartString = [[NSString alloc] initWithData:serializedData encoding:NSUTF8StringEncoding];
}
NSLog(#"%#", shoppingCartString);
//Now that the cart is converted into a string. it is ready for transport
NSURL *url = [NSURL URLWithString:#"ftp://username:password#domainName.com/folder/serializedCart.xml"];
BOOL OK =[shoppingCartString writeToURL:url atomically:NO encoding:NSUTF8StringEncoding error:&error];
if(!OK) {
NSLog(#"Error writing to file %# , error = %#", url, [error localizedFailureReason]);
}
I'm getting the following console output for this code:
Error writing to file ftp://username:password#domainName.com/folder/serializedCart.xml , error = (null)
One of the variables: _domain in this error object in the last line when, I mouse over it during debugging says NSCocoaErrorDomain
I'm not sure how to debug this.
Could someone give any suggestions?
The writeToURL:.. methods don't support the FTP protocol. You'll have to use other mechanisms to write the string content onto an ftp server. You can look at tools such as ios-ftp-server to handle such uploads. You can also look at this sample code from Apple.
Related
I'm trying to parse the JSON file at this URL: http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22%2C%22AAPL%22%2C%22GOOG%22%2C%22MSFT%22)%0A%09%09&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=results
The code that I have so far is as follows:
NSData *data=[NSData dataWithContentsOfURL:[[NSURL alloc] initWithString:url]];
NSError *error = nil;
id myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#", error);
NSArray *jsonArray = (NSArray *)myJSON;
for (id element in jsonArray) {
NSLog(#"Element: %#", [element description]);
}
This code seems to come up with an error each time (ERROR 3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)").
I'm wondering if this is a problem with the way that I'm downloading/parsing the data or if it's a problem within the actual JSON in which I have to approach it in a different matter.
Remove the &callback=results at the end of the URL. This causes the JSON to not start with an array or dictionary. Just be aware that if you are referencing "results" in your JSON code then you will need to remove/change that. If you diff the two JSON texts then you will see the difference (look at the beginning).
in a web browser open the result of the url you posted copy the contents then go to jsonlint.com and paste the contents then click validate. it shows you that the input is not valid json so you might have to do some additional parsing.
I have this problem when I fetch an XML file from the internet and then parse it, where I get this error:
Error while parsing the document: Error Domain=SMXMLDocumentErrorDomain Code=1 "Malformed XML document. Error at line 1:1." UserInfo=0x886e880 {LineNumber=1, ColumnNumber=1, NSLocalizedDescription=Malformed XML document. Error at line 1:1., NSUnderlyingError=0x886e7c0 "The operation couldn’t be completed. (NSXMLParserErrorDomain error 5.)"}
Here is an extract from the code (I believe I am only showing the most relevant code, if you need more, please ask.)
// Create a URL Request and set the URL
NSURL *url = [NSURL URLWithString:#"http://***.xml"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// Display the network activity indicator
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
// Perform the request on a new thread so we don't block the UI
dispatch_queue_t downloadQueue = dispatch_queue_create("Download queue", NULL);
dispatch_async(downloadQueue, ^{
NSError* err = nil;
NSHTTPURLResponse* rsp = nil;
// Perform the request synchronously on this thread
NSData *rspData = [NSURLConnection sendSynchronousRequest:request returningResponse:&rsp error:&err];
// Once a response is received, handle it on the main thread in case we do any UI updates
dispatch_async(dispatch_get_main_queue(), ^{
// Hide the network activity indicator
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
if (rspData == nil || (err != nil && [err code] != noErr)) {
// If there was a no data received, or an error...
NSLog(#"No data received.");
} else {
// Cache the file in the cache directory
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString* path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"init.xml"];
//NSLog(#"%#",path);
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
[data writeToFile:path atomically:YES];
//NSString *sampleXML = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"xml"];
NSData *data = [NSData dataWithContentsOfFile:path];
// create a new SMXMLDocument with the contents of sample.xml
NSError *error;
SMXMLDocument *document = [SMXMLDocument documentWithData:data error:&error];
// check for errors
if (error) {
NSLog(#"Error while parsing the document: %#", error);
// return;
}
Firstly, I have connected the iPhone to an XML feed which it has fetched and written to the path of the variable path. Then I check for errors in the XML document and I get that error every time.
However, if I use a local XML file which I have placed in the main folder of my application there is no problem fetching all the data.
Using the code:
NSString *sampleXML = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"xml"];
So does anyone have an idea as to what I can have done wrong? It seems as if it doesn't download and store the XML file to the iPhone's cache, however NSLog(); seems to show it differently. Obviously the local file is the same as the file on the internet.
Furthermore, I already tried to save the file to the path without any results, though.
A couple of observations:
The key issue would appear to be that you retrieved the data in rspData, but when you write it to your temporary file, you're writing data, not rspData. So change the line that says:
[data writeToFile:path atomically:YES];
to
[rspData writeToFile:path atomically:YES];
Frankly, I don't even see the data variable defined at that point (do you have some ivar lingering about?). I'd be ruthless about getting rid of any ivars or other variables that you don't need, so that you don't accidentally refer to some unused variable. Anyway, just use the rspData that you retrieved rather than some other variable.
Why are you even writing that to a file, only to then read the file into another NSData that you pass to your XML parser? That seems entirely unnecessary. Just go ahead and use the rspData you initially retrieved. If you want to save the NSData to a file so you can examine it later for debugging purposes, that's fine. But there's no point in re-retrieving the NSData from the file, as you already have it in a rspData already.
If you encounter these errors in the future, feel free to examine the contents of the NSData variable with a debugging line of code, something like:
NSLog(#"rspData = %#", [[NSString alloc] initWithData:rspData encoding:NSUTF8StringEncoding]);
When you do that, you can look at the string rendition of the NSData, and usually the problem will become self evident.
As a complete aside, in your debugging error handler, you have a line that says:
NSLog(#"No data received.");
I might suggest you always include any errors that might be provided, e.g.:
NSLog(#"No data received: error = %#", err);
iOS provides useful error messages, so you should avail yourself of those.
I have an app that just opened call a webserver page that gives me a json string.
When I'm on the local network all works without problem but when I open the app outside the local network and without vpn the app crashes.
How can I control the json string?
This is my code:
NSString *urlstr = [[NSString alloc] initWithFormat:#"%#yes.php", av];
NSURL *url = [[NSURL alloc] initWithString:urlstr];
NSError* error = nil;
NSString* urlString = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
NSString *newStr;
NSData* data=[newStr dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
sn1 = [[json objectForKey:#"Rele1"] intValue];
I want to compare the json answer with a NULL value, if the two parameters are equal I show an alert.
EDIT: If I try to read any value, the app crashes waiting the json reply...
I have bypassed the problem with an NSURLRequest with the timeoutInterval parameter that closes the connection after n seconds.
Amongst other things, you fail to:
check whether the attempt to fetch an ASCII-encoded string from a remote URL failed (obvious possibilities: the URL is unreachable, the result is UTF-8 rather than ASCII);
check whether the JSON parsing succeeds (obvious possibility: the server 404d and returned an HTML error page instead)
check whether the returned JSON object was actually a dictionary (eg, it could be an array, in which case calling objectForKey: on it will raise an exception)
The parsing of return data as ASCII then re-encoding into UTF-8 is also probably redundant — because the one supersets the other it has the effect of a threshold test, otherwise preventing acceptable results from proceeding.
Does this code ever worked?
You should check error after [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error];
you are reading URL data into urlString but then get NSData from uninitialized newStr and parse it?
again you should always check error whenever you provide it before anything else
why do you read the data as ASCII but the NSData as UTF8?
I want to send json service when the user search text on searchbar. Here the issue is that I return null value of NSData object, what the issue is here? If I define the same url which I print in console that works but what's the issue here?
-(void)doIt{
NSURL *url = [NSURL URLWithString:weburls];
NSData *data =[NSData dataWithContentsOfURL:url];
[self getData:data];
}
If I will write like that then it works, but I want to call the service on the searchbar event but there is a problem
NSString *weburl = [NSString stringWithFormat:#"%#%#",
#"http://192.168.1.196/ravi/iphonephp?mname=",searchText];
NSLog(#"%#",weburl);
NSURL *url = [NSURL URLWithString:weburl];
NSLog(#"the url is : %#",url);
NSError *error;
NSData *data =[NSData dataWithContentsOfURL:url options:nil error:&error];
NSLog(#"Data is :%#",data);
NSLog(#"the Error massage is : %#",error);
[self getData:data];
Gives me console value like
customCellDemo[1553:f803] the url is : http://192.168.1.196/ravi/iphonephp?mname=a
2012-03-16 15:26:36.259 customCellDemo[1553:f803] Data is :(null)
2012-03-16 15:26:43.624 customCellDemo[1553:f803] the Error massage is : Error
Domain=NSCocoaErrorDomain Code=256 "The operation couldn’t be completed. (Cocoa error 256.)"
UserInfo=0x6ab2760 {NSURL=http://192.168.1.196/ravi/iphonephp?mname=a}
From the manual of dataWithContentsOfURL;
Return Value: A data object containing the data from the location
specified by aURL. Returns nil if the data object could not be
created.
In other words, it can either not create an NSData (unlikely) or it can probably not get any data from your supplied URL. I suggest you try to use dataWithContentsOfURL:options:error: instead to get an error code and be able to diagnose the problem.
I am attempting to create a .xml file and set the contents of the file to equal a predetermined string.
I have built the XML and am currently storing it in an NSString.
I want to put the contents of this string into a file with the extension of .xml and send an email with the file as an attachment.
I am able to email PDFs and assumed creating the file with an extension of .xml would be the easy bit, but alas I cannot do it.
If anyone could offer a helping hand I would be much appreciative.
Try something like this:
NSString *path = ...;
NSString *string = ...;
NSError *error;
BOOL ok = [string writeToFile:path atomically:YES encoding:NSUnicodeStringEncoding error:&error];
if (!ok) {
// an error occurred
NSLog(#"Error writing file at %#\n%#",path, [error localizedFailureReason]);
// implementation continues ..
Writing to Files and URLs