how to request url to execute or connect to server .. what i was using not working..
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@%@%@%@%@%@%@%@%@",[ConfigDB valueForKey:@"mailURL"], @"?ownerID=", [ConfigDB ownerID], @"&userid=开发者_运维技巧",[ConfigDB userID],@"&pID=",pid,@"&emailAddress=",emailTxtField.text,[ConfigDB valueForKey:@"showEmailFlag"]]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
That's quite a stringWithFormat
message! The first thing to check is that you're getting a URL that matches your expectations.
Once you've got a URL request object—and consider using a regular NSURLRequest
, it should be faster and it doesn't look like you're intending to reuse this object:
// already autoreleased
NSURLRequest *request = [NSURLRequest requestWithURL:url];
Then you need to actually make the request. There are two approaches here. You'll use NSURLDownload
if you're looking to save the request to file. It looks like you're looking to make a GET
request to an email server of some sort, so you probably want the other approach: NSURLConnection
.
NSURLConnection
is mostly intended for asynchronous requests. You provide a delegate with some methods and your NSURLConnection will use those methods to let you know when the communication is done; whether there were errors; etc.
Add a property to your view controller class for the connection, and an NSMutableData
property as well. You will start your connection with (assuming that your current class is also your delegate):
// initialize our storage for the file
self.downloadData = [NSMutableData dataWithLength:1024];
// create and start the connection
self.urlConnection = [NSURLConnection connectionWithRequest:request delegate:self];
if(nil == self.urlConnection) {
NSLog(@"Couldn't create connection to url %@", url);
}
In your code somewhere—probably your current view controller—you'll need to implement those methods:
-(void) connection:(NSURLConnection*)connection didReceiveData:(NSData*)data {
// if you have more than one NSURLConnection in this class, test against the
// connection parameter
[downloadData appendData:data];
}
-(void) connectionDidFinishLoading:(NSURLConnection*)connection {
// download completed successfully, we can do what we like with the downloadData object now
// ...
}
-(void) connection:(NSURLConnection*)connection didFailWithError:(NSError*)error {
// handle failure with the grace of Audrey Hepburn. probably log something, too
}
精彩评论