IOS 5中最简单的发起HTTP GET请求的方式是什么?

4

我正在尝试从我的应用程序向我的Web服务器上的php文件发送建议。我已经在浏览器中测试了php脚本,它可以向用户发送电子邮件并将建议存储在我的数据库中,这一切都很正常。当运行以下脚本时,我通过IOS获得了成功的连接,但是我没有在我的数据库中收到结果。

NSString *post = [NSString stringWithFormat:@"http://blahblah.com/suggest.php?s=%@&n=%@&e=%@", suggestion, name, email];

    // Create the request.
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:post]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];

    // create the connection with the request
    // and start loading the data
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if (theConnection) {

        NSLog(@"Connection establisted successfully");

    } else {

        NSLog(@"Connection failed.");

    }

我已经检查了所有字符串,并将所有空格编码为%20等。有没有人能看出我的脚本为什么不起作用的明显原因?
从我的应用程序中发出HTTP请求而不打开Safari的最简单方法是什么?
1个回答

7
你的问题在于你创建了连接,但没有发送实际的“连接”请求。请改为:
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

尝试使用这段代码:

NSURLResponse* response = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil]

这是一种快速而简单的解决方案,但要记住,在此连接过程中,您的UI线程将看起来被冻结。 想要避免这种情况,可以使用异步连接方法,这比上述方法稍微复杂一些。在网上搜索NSURLConnection send asynchronous request,答案就在那里。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接