Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x9eaa6b0 - ios6

When start NSURLConnection some times I am getting these error.
But, not always get this error.
Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x9eaa6b0 {NSUnderlyingError=0xae8c730 "bad URL", NSLocalizedDescription=bad URL}

There is space in the url is reason for that mistake.
NSString *urlString =[NSString stringWithFormat:#"&street=%#&street2=&city=%#&state=%#&
zipcode=%#&candidates=10", address.address2,address.city, address.state, address.zip5];
NSLog(#"BAD URL - %#",urlString ); // there is space in url
NSString *encodedUrl = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSLog(#" CORRECT URL - %#", encodedUrl); // url encode that space by %20
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL RLWithString:encodedUrl]];

Related

How to access a field in struct

I have the following code in my Xcode project:
- (BOOL)getIP;
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://httpbin.org/ip"]];
request.HTTPMethod = #"GET";
[request setValue:#"TestValue" forHTTPHeaderField:#"Test"];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"getIP returns = %#", dict);
return NO;
}
When I set a breakpoint in lldb using the "breakpoint set -b CFURLRequestSetHTTPHeaderFieldValue" command and trigger the getIP method, the code stops as expected.Then I intput the "po $x0
" lldb command and it prints "<CFMutableURLRequest 0x1741bff00 [0x1a7808bb8]> {url = http://httpbin.org/ip, cs = 0x0}".
What I want to know is: 1.how to access the url filed in struct CFMutableURLRequest; 2.how to get the definition of struct CFMutableURLRequest.
Thanks in advance!
The po command shows you the result of the description message sent to the object. There's no guarantee that the text printed by descriptionis telling you about particular ivars in the object, it's just some free-form text that the class author can fill with whatever she best thinks describes the object. The fact that it says "url =" doesn't mean there actually is an ivar called url.
You can use the p or expr commands to print the contents of the object (at least so far as that is available to the debugger.) Since this is a pointer, you'll want to do:
(lldb) p *request
In this case, it looks like these are opaque objects - the debug information doesn't say how they are laid out. So the debugger can't really help you look into the object directly.

Get File Size at URL Objective-C

I'm looking for a way to get the file size of a specific file at an NSURL address. This is what I have tried but it always returns '0' in the log output:
NSString *url = #"http://www.examplesite.com/file01.zip";
unsigned long long fileSize1 = [[[NSFileManager defaultManager] attributesOfItemAtPath:[url lastPathComponent] error:nil] fileSize];
NSLog(#"size of %# in bytes === %llu", [url lastPathComponent], fileSize1);
After searching some on I found this solution. It finds the file size of the file on the server and shows the result in the log.
NSString *url = #"http://www.examplesite.com/file01.zip";
NSURL *URL = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
[request setHTTPMethod:#"HEAD"];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error: nil];
long long size = [response expectedContentLength];
NSLog(#"File size before download: %lld",size);

NSURL custom scheme trouble

I wrote below code to programmatically load a URL in UIWebview.
NSString *urlStr = [NSString stringWithFormat:#"app-api://camera_button(%#)", #"{\"date\":\"2014-05-26\",\"referer_url\":\"http://google.com",\"abort_url\":\"http://google.com"}"];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]]];
And in the webView's delegate method webView:shouldStartLoadWithRequest:navigationType: , I found the url being loaded has been changed to 'file://app-api://......'. But what I needed is 'app-api:......'. Anyone can tell me what the problem is ? Thanks in advance.
Ok if problem in URL string, then use following code (stringByAddingPercentEscapesUsingEncoding)
NSString *urlString = [NSString stringWithFormat:#"URL_STRING"];
NSURL *finalURL = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
EDITED
You can remove file:// from your url string by using following code
NSString *selectedRequest = "MY URL STRING";
NSString *requestString = [selectedRequest stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *finalString = [requestString stringByReplacingOccurrencesOfString:#"file://" withString:#""];
NSLog(#"%#", finalString);

Adding data given by the user to an array - Objective-C

I'm trying to create a Mac OS X app where there are some default sound and the user can add others if he wants. I'm loading the sounds to an array in -awakeFromNib :
for (NSString *str in [PreferencesController beats]) {
resourcePath = [[NSBundle mainBundle] pathForSoundResource:str];
beat = [[NSSound alloc] initWithContentsOfFile:resourcePath byReference:YES];
[beat setLoops:YES];
[beat setName:str];
[beatsArray addObject:beat];
}
Everything works fine until the app tries to add to the array a sound added by the user. It says : *** -[NSURL initFileURLWithPath:]: nil string parameter. I'm guessing that it can't find the URL of the file but I'm copying the file to the app's directory when the user selects it by the following code :
if ( [openDlg runModalForTypes:[NSArray arrayWithObjects:#"aif",#"aiff",#"mp3",#"wav",#"m4a",nil]] == NSOKButton)
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSString *dataPath = [[NSBundle mainBundle] bundlePath];
NSLog(#"Datapath is %#", dataPath);
NSLog(#"Selected Files : %#",[[openDlg URLs] objectAtIndex:0]);
[fileManager copyItemAtURL: [[openDlg URLs] objectAtIndex:0] toURL: [NSURL fileURLWithPath: [[NSBundle mainBundle] bundlePath]] error:&error];
NSLog(#"File copied");
NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:[PreferencesController beats]];
NSString *fileName = [[[openDlg URL] path] lastPathComponent];
NSArray *fileNameArray = [fileName componentsSeparatedByString:#"."];
[newArray addObject:[fileNameArray objectAtIndex:0]];
NSLog(#"%#",newArray);
[PreferencesController setBeats:newArray];
[self awakeFromNib];
[_tableView reloadData];
}
What's wrong with this code?
Looks like you're trying to copy a file to a folder because you're just using the bundle path as the destination URL. The destination URL needs to specify the full path including the destination file name.
Try logging the error when the file is copied:
NSLog(#"File copied with error: %#", error);
This line contains the error:
[fileManager copyItemAtURL: [[openDlg URLs] objectAtIndex:0] toURL: [NSURL fileURLWithPath: [[NSBundle mainBundle] bundlePath]] error:&error];
Specifically, the problem is that the destination URL is a folder:
[[NSBundle mainBundle] bundlePath]
It should be something like:
[[[NSBundle mainBundle] bundlePath] stringByAppendingString:[[[[openDlg URLs] objectAtIndex:0] path] lastPathComponent];
Then, once you have it working, as #Abizern says in the comments, saving to the bundle is a bad idea (it's part of the app).
Once you have it working, you should choose a better location to save the sounds to (like a support document folder for the app, Programmatically get path to Application Support folder)

The easiest way to write NSData to a file

NSData *data;
data = [self fillInSomeStrangeBytes];
My question is now how I can write this data on the easiest way to an file.
(I've already an NSURL file://localhost/Users/Coding/Library/Application%20Support/App/file.strangebytes)
NSData has a method called writeToURL:atomically: that does exactly what you want to do. Look in the documentation for NSData to see how to use it.
Notice that writing NSData into a file is an IO operation that may block the main thread. Especially if the data object is large.
Therefore it is advised to perform this on a background thread, the easiest way would be to use GCD as follows:
// Use GCD's background queue
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// Generate the file path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"yourfilename.dat"];
// Save it into file system
[data writeToFile:dataPath atomically:YES];
});
writeToURL:atomically: or writeToFile:atomically: if you have a filename instead of a URL.
You also have writeToFile:options:error: or writeToURL:options:error: which can report error codes in case the saving of the NSData failed for any reason. For example:
NSError *error;
NSURL *folder = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:true error:&error];
if (!folder) {
NSLog(#"%s: %#", __FUNCTION__, error); // handle error however you would like
return;
}
NSURL *fileURL = [folder URLByAppendingPathComponent:filename];
BOOL success = [data writeToURL:fileURL options:NSDataWritingAtomic error:&error];
if (!success) {
NSLog(#"%s: %#", __FUNCTION__, error); // handle error however you would like
return;
}
The easiest way, if you want to do this a few times manually instead of coding, is to only use your mouse:
Put a breakpoint one line after your NSdata are fulfilled.
Hold your mouse over your NSData variable, click on the Eye button, and then export.
After that chose the storage details (name/extension/location of the file).
Click on "Save" and you are done!

Resources