如何请求url连接

时间:2010-08-14 21:14:18

标签: iphone objective-c xcode url

如何请求url执行或连接到服务器.. 我用的不工作..

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];

1 个答案:

答案 0 :(得分:1)

这是一条stringWithFormat消息!首先要检查的是,您获得的网址符合您的预期。

一旦你有一个URL请求对象 - 并考虑使用常规NSURLRequest,它应该更快,看起来你不打算重用这个对象:

// already autoreleased
NSURLRequest *request = [NSURLRequest requestWithURL:url];

然后你需要实际提出请求。这里有两种方法。如果您要将请求保存到文件,则将使用NSURLDownload。看起来您正在寻求向某种电子邮件服务器发出GET请求,因此您可能需要另一种方法:NSURLConnection

NSURLConnection主要用于异步请求。您为委托提供了一些方法,NSURLConnection将使用这些方法让您知道通信何时完成;是否有错误;等

为视图控制器类添加属性以进行连接,并添加NSMutableData属性。您将开始连接(假设您当前的班级也是您的代表):

// 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);
}

在您的代码中 - 可能是您当前的视图控制器 - 您需要实现这些方法:

-(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
}