What is real issue with the NSData in my code - iphone

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.

Related

Parsing Local XML File Works, Downloaded XML File Doesn't

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.

JSON returning null

I'm having a bit of trouble parsing some returned JSON. I'm fairly new to working with JSON. I'm trying to get the company name from the first JSON array element. I have a feeling that I'm confusing the use of NSMutabeArray and NSMutableDictionary. What I get is null. Any idea what I'm doing wrong?
NSString *url = #"http://www.google.com/finance/info?infotype=infoquoteall&q=C,JPM,AIG,AAPL";
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: url]];
//parse out the json data
NSError* error;
NSMutableArray* json = [NSJSONSerialization
JSONObjectWithData:data //1
options:kNilOptions
error:&error];
NSString* companyName = [[json objectAtIndex:0] objectForKey:#"name"] ; //Where I need some help
NSLog(#"we got %#", companyName);
Load that url in your browser. Looks like google is prefixing the JSON with //. I think NSJSONSerialization is tripping on that. Try this
NSRange range = NSMakeRange(2, [data length] - 3);
NSData *noPrefix = [data subdataWithRange:range];
Then send that to the parser.
You put in an error object, but you never looked at it. If you had, you would see that the data is corrupted:
Error Domain = NSCocoaErrorDomain Code = 3840 "The data couldn’t be read because it has been corrupted." (Invalid value around character 1.) UserInfo = 0x10030a8f0 { NSDebugDescription = Invalid value around character 1. }
I changed the value of the options parameter to see this error. I have
NSMutableArray* json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers |NSJSONReadingAllowFragments error:&error];

Can't convert app bundle to NSData

I'm trying to convert my bundle to NSData so that I can hash the data and have a server verify the hash before allowing downloads. The only problem is that when I try to convert the bundle to NSData, I get Error: The operation couldn’t be completed. (Cocoa error 257.) I looked up error 257 and it means that the bundle couldn't be read due to a permissions problem. What am I doing incorrectly? Thanks for your help.
NSString *bundlePath = [[NSBundle mainBundle] resourcePath];
NSLog(#"%#", bundlePath);
NSError *error;
NSData *bData = [NSData dataWithContentsOfFile:bundlePath options:nil error:&error];
NSLog(#"Error: %#", [error localizedDescription]);
If piracy protection is your ultimate goal, refer to this for a little insight and code.
http://thwart-ipa-cracks.blogspot.com/2008/11/detection.html?m=1

Get image bytes

I am trying to load the bytes of an image like this:
NSURL *img = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"img" ofType:#"png"] isDirectory:NO];
NSString * test = [NSString stringWithContentsOfFile:[img absoluteString] encoding:NSASCIIStringEncoding error:&err];
But I always get following error:
Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn\u2019t be completed.
(Cocoa error 260.)" UserInfo=0xc02abf0
{NSFilePath=file://localhost/Users/admin/Library/Application%20Support/iPhone%20Simulator/4.3.2/Applications/C55551DB-152A-43D6-A1E0-9845105709D6/myApp.app/img.png,
NSUnderlyingError=0xc02ccc0 "The operation couldn\u2019t be completed. Folder or file does not exist"}
However the file DOES exist, and if I copy/paste the NSFilePath into the browser it finds the image. What could be wrong?
Why not
NSString *path = [[NSBundle mainBundle] pathforResource:#"img" ofType:"png"];
NSData *data = [NSData dataWithContentsOfFile:path];
You can't just store random bytes in an NSString - it will try to convert them into a string and might fail. You need to use an NSData object for binary data.
You also don't need to use NSURLs at all; NSBundle will give you a path as a string.
As you are using the file URL, use [img path] instead of [img absoluteString] in the second line.
Or use [NSURL URLWithPath] in the first line.
Store bytes in NSData:
NSData *bytes = UIImagePNGRepresentation([UIImage imageNamed:#"myImage.png"]);
NSData* imageData = UIImagePNGRepresentation("imagename.."); //the image is converted to bytes

Sending string via ftp : getting error

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.