what is the difference between NSURLConnection and NSURL?
i mean if i am downloading a file, does it make and difference which one i use?
Rgds
for:
NSString *myUrl = #"http://www.test.com/";
NSString *returnData = [NSString stringWithContentsOfURL:[NSURL URLWithString: myUrl]];
or
NSString *myUrl = #"http://www.test.com/";
NSURLRequest *myRequest = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString:myUrl] ];
NSString *returnData = [NSURLConnection sendSynchronousRequest:myRequest returningResponse: nil error: nil ];
whats the difference?
thks
The Connection
An NSURLConnection object provides support to perform the loading of a URL request.
The Request
NSURLRequest objects represent a URL load request in a manner independent of protocol and URL scheme.
E.g. requestWithURL:
Creates and returns a URL request for a specified URL with default cache policy and timeout value.
+ (id)requestWithURL:(NSURL *)theURL
The URL
The NSURL class provides a way to manipulate URLs and the resources they reference. NSURL objects understand URLs as specified in RFCs 1808, 1738, and 2732. ...
To get the contents of a URL, NSString provides stringWithContentsOfURL: and NSData provides dataWithContentsOfURL:.
References:
NSURLConnection_Class/Reference/Reference.html
NSURL_Class/Reference/Reference.html#//apple_ref/doc/c_ref/NSURL
Best thing about NSURLConnection is its asynchronous behaviour so that you dont have to wait until the url is loaded.
Related
i have this in Xcode:
NSString *post =[[NSString alloc] initWithString:#"message";
this string i want to send to myadress.php. anybody help me with some good reference or code please.
this is my php side:
<?
$connect = mysql_connect ("$dbserver", "$dbuser", "$dbpass");
mysql_select_db("$dbname") or die(mysql_error());
$feed = $_GET['feed_message'];
$login = mysql_query("INSERT INTO feedback SET feed_message ='".$feed."'", $connect) or die(mysql_error());
mysql_close($connect);
?>
You can try this and you need implement the NSURLConnection delegate method
NSURL *url = [NSURL URLWithString:#"http://yoururl"];
NSURLRequest *urlReq = [NSURLRequest requestWithURL:url];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlReq delegate:self];
[connection start];
You can also use ASIHttpRequest, it has more Features.
In fact you just want to send a request to specific URL containing parameter "feed_message":
http://myserver.com/myscrypt.php?feed_message=message
To do it you need:
a. Create an url:
NSString * scriptURLString = #"http://myserver.com/myscrypt.php";
NSString * parameterName = #"feed_message";
NSString * post = #"message";
NSString * urlString = [NSString stringWithFormat:#"%#?%#=%#",scriptURLString, parameterName, post];
NSURL * url = [NSURL URLWithString:urlString];
b. send request to url. There are many ways to do it depending on your needs.
You may send asynchronous request (set delegate property and implement delegate methods to handle results)
[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url] delegate:nil];
or simply use NSData synchronous method:
[NSData dataWithContentsOfURL:url];
I am trying to send a query as part a the URL to obtain an XML file, and then trying to parse the XML file using NSXMLParser and initWithContentsOfURL. However the parser is not able to parse the file. I tested the parser with the same file, but this time the file was saved on the server (it was not being generated) and it worked just fine, so I know it is not a problem with the parser.
I have come to think that it does not parse it because I need to load the file before I try to parse it, or give the initWithContentsOfURL time to load the contents. So I tried to put those contents in a NSString and a NSData and using a sleep function as well as using a block but that did not work either.
What would be the best way to go about this problem?
Here is some of the code:
NSString *surl = [NSString stringWithFormat:#"http://lxsrv7.oru.edu/~maria_hernandez/query.xml"];
url = [NSURL URLWithString:surl];
NSString *curl = [[NSString alloc] initWithContentsOfURL:url];
NSLog(#"URL: %#", surl);
NSLog(#"URL Content: %#", curl);
SXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:receivedData];
//Other stuff we have tried:
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:surl] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLResponse = nil;
NSError = nil;
receivedData = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &theResponse error: &error];
Let me know if you have more questions or if you wish to see more code.
Thanks!
have you tried setting a delegate for the NSXMLParse that implements the NSXMLParserDelegate which has events for parsing the document
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSXMLParser_Class/Reference/Reference.html
I am trying to access an XML file store in the resources directory. I am using NSURL to access this file using NSURLConnection( this file is going to be swapped out for a remote service in the future).
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:#"file:///XMLTest.xml"]
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *connection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
response = [[NSMutableData data] retain];
} else {
NSLog(#"Could not create connection");
}
The class that starts the connection implements the NSURLConnection methods:
connection:willCacheResponse:
connection:didReceiveData:
connectionDidFinishLoading:
connectionDidFinishLoading:
Once I launch this the simulator dies, no messages are printed to the console so I am at a loss for where to look. Any ideas, or am I just doing this completely wrong?
Trying to load anything from the filesystem root is wrong, wrong, wrong. Definitely wrong on the device, and probably wrong on the simulator. The resources directory should be accessed via the NSBundle class.
For example, to get a URL for a file called "Data.txt" in the resources, use the following:
NSURL *MyURL = [[NSBundle mainBundle]
URLForResource: #"Data" withExtension:#"txt"];
If you want to get a URL from a path (say, because you created a file in NSTemporaryDirectory() and you need to get that as a URL) you can easily do so by using NSURL's fileURLWithPath method:
NSString* tempPath = NSTemporaryDirectory();
NSString* tempFile = [tempPath stringByAppendingPathComponent:fileName];
NSURL* URL = [NSURL fileURLWithPath:tempFile];
Much easier than +URLWithString: and other methods.
This would also work:
Obj-C
NSString *path = [[NSBundle mainBundle] pathForResource:#"XMLTest" ofType:#"xml"];
Swift 5
let url = Bundle.main.url(forResource: "XMLTest", withExtension: "xml")!
Hope this helps!
You can try this
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"file://localhost/Users/userName/Desktop/XMLTest.xml"]];
here assuming file is in desktop.
Swift 3:
let myFileName = "somefilename"
let myURL = Bundle.main.url(forResource: myFileName, withExtension: "png")
Whats the best way to make this a more secure and less obvious security risk?
NSString *loginIdentification = [NSString stringWithFormat:#"user=%#&pass=%#&", userNameLogin, passWordLogin];
addressVariable = [NSString stringWithFormat:#"%#/%#", url, loginIdentification];
addressVariable = [addressVariable stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
Make sure you're using an https connection and not an http connection.
Instead of putting the sensitive information in the URL (via GET), use the POST method and put them in the body. That way, they won't show up in your server logs.
Say I want to get the HTML of
http://www.google.com
as a String using some built-in classes of the Cocoa Touch framework.
What is the least amount of code I need to write?
I've gotten this far, but can't figure out how to progress. There must be an easier way.
CFHTTPMessageRef req;
NSURL *url = [NSURL URLWithString:#"http://www.google.com"];
req = CFHTTPMessageCreateRequest(kCFAllocatorDefault,
CFSTR("GET"),
(CFURLRef)url,
kCFHTTPVersion1_1);
The quickest way is to use NSString's +stringWithContentsOfURL: method. However, this is a modal call, and your application will be non-responsive while it runs. You can either move it to a background thread, or use the NSURLConnection class to make a proper, asynchronous request.
One way to do this is as follows, however as Ben Gottlieb points out, this is a synchronouseRequest and will cause your program's execution to wait on the return of this function call, possibly making your application non-responsive.
NSURL *url = [ NSURL URLWithString: #"http://www.google.com"];
NSURLRequest *req = [ NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30.0 ];
NSError *err;
NSURLResponse *res;
NSData *d = [ NSURLConnection sendSynchronousRequest:req
returningResponse:&res
error:&err ];
You can find information on writing the proper delegate methods to handle a Asynchronous Connection here on the Apple dev-docs.