objective-c - userDefaults 中的值未填充 URL 查询字符串

标签 objective-c ios

我正在制作这个聊天应用程序,与我的网络服务器上的 .php 文件一起使用,以将数据存储在 SQL 数据库中

这是迄今为止我的代码:

#import "vtchatViewController.h"

@interface vtchatViewController ()

@end

@implementation vtchatViewController

@synthesize messageBox, messageView, Send, Refresh;


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    NSString *usrName = [[NSUserDefaults standardUserDefaults] stringForKey:@"user_name"];

    NSURL *url = [NSURL URLWithString:@"http://server.com/ios/messages.php"];  [messageView loadRequest:[NSURLRequest requestWithURL:url]];

}

- (IBAction)refreshButton:(id)sender {
    NSURL *url = [NSURL URLWithString:@"http://server.com/ios/messages.php"];  [messageView loadRequest:[NSURLRequest requestWithURL:url]];

}

- (IBAction)sendButton:(id)sender {
    // server.com/ios/add.php?user=Username here&message=Message Her

    [messageBox resignFirstResponder];
    NSString* urlString = [[NSString stringWithFormat:@"http://server.com/ios/add.php?user=",usrName "&message=%@", messageBox.text] stringByAddingPercentEscapesUsingEncoding : NSUTF8StringEncoding];
    NSURL *add = [NSURL URLWithString:urlString];



    [messageView loadRequest:[NSURLRequest requestWithURL:add]];
    messageBox.Text = @"";


}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

但是,在“viewDidLoad”行上,我无法让它使用我的设置包中的用户名:

NSString* urlString = [[NSString stringWithFormat:@"http://server.com/ios/add.php?user=",usrName "&message=%@", messageBox.text] stringByAddingPercentEscapesUsingEncoding : NSUTF8StringEncoding];
NSURL *add = [NSURL URLWithString:urlString];

我收到错误“使用未声明的标识符“usrName”,而且我也不知道我是否确实实现了正确的“usrName”以供在此使用

我只需要它来将数据发送到“server.com/ios/add.php?”其中数据应采用以下格式:“user=此处的用户名&message=此处的消息”

如果我只使用固定的用户名,我就可以使用它,但正如所说,我不知道如何使该东西使用存储在我的设置文件中的用户名

提前致谢

最佳答案

您需要使用字符串格式标记来将用户名插入到 urlString 变量中,如下所示:

NSString* urlString = [[NSString stringWithFormat:@"http://server.com/ios/add.php?user=%@&message=%@", usrName, messageBox.text];

这应该可以帮助您理解为什么格式字符串不起作用以及为什么会出现该错误。我上面的代码没有转义 usrNamemessageBox.text 的值,因此您需要将它们添加回您的代码中。

关于objective-c - userDefaults 中的值未填充 URL 查询字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13015154/

相关文章:

objective-c - Objective C 是纯粹的面向对象语言吗?

ios - 推送到下一个 viewController 时导航栏消失

ios - 无法通过测试用例 iOS 将数据插入 sqlite 数据库

ios - UICollectionView.dequeueReusableCell 崩溃

iphone - UIActivityViewController 不显示 "save to camera roll"选项

Objective-C 2.0;分配属性(property);内存泄漏?

ios - 将大数字四舍五入到最接近的百位, float 正在失去值(value)

ios - 遍历电话号码,创建自定义 View 并 swift 将电话号码传递给它

ios - 如何在 CoreBluetooth 上同时向多个蓝牙 LE 从设备写入数据?

objective-c - 如何在 iOS < 4 中停止 UIView 动画