将UITextField附加到NSUserDefaults

时间:2015-01-01 11:20:40

标签: json nsstring uitextfield nsuserdefaults server

我是初学者&我试图弄清楚如何将文本从文本字段上传到服务器以及坐标,但我需要将文本字段添加到userdefaults。

UITextfield位于我的ViewController中,而坐标& post to server位于一个单独的对象类中。

教程或示例代码将非常有用。

下面,我附上了我用来上传坐标的相关代码。

我需要的是帮助将另一个类中的UITextfield中的文本添加到上面的代码中。

Singleton.m

@implementation Singleton {
    CLLocation *location;
    CLLocationManager *locationManager;
    NSMutableData *responseData;
}

- (id)init {
    if (self = [super init]) {

        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setDouble:location.coordinate.latitude forKey:@"latitude"];
        [userDefaults setDouble:location.coordinate.longitude forKey:@"longitude"];

        [userDefaults synchronize];

    }
    return self;
}

- (void) timerDidFire:(NSTimer *)timer
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    if (([userDefaults doubleForKey:@"latitude"] != location.coordinate.latitude) || ([userDefaults doubleForKey:@"longtitude"] != location.coordinate.longitude)) {

        NSMutableURLRequest *request = [NSMutableURLRequest
                                    requestWithURL:[NSURL URLWithString:@"http://setslocation.php"]];

        NSDictionary *requestData = [[NSDictionary alloc] initWithObjectsAndKeys:
                                 [NSString stringWithFormat:@"%f", location.coordinate.longitude], @"longitude",
                                 [NSString stringWithFormat:@"%f", location.coordinate.latitude], @"latitude",
                                 nil];
        NSError *error;
        NSData *postData = [NSJSONSerialization dataWithJSONObject:requestData options:0 error:&error];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPMethod:@"POST"];
        [request setHTTPBody:postData];
        [NSURLConnection connectionWithRequest:request delegate:self];

        [userDefaults setDouble:location.coordinate.latitude forKey:@"latitude"];
        [userDefaults setDouble:location.coordinate.longitude forKey:@"longtitude"];
        [userDefaults synchronize];
    }
}

1 个答案:

答案 0 :(得分:3)

首先将文本字段值保存到NSUserDefaults并进行同步。您可以从NSUserDefaults中获取项目中的任何值。

设置值如:

  [[NSUserDefaults standardUserDefaults] setObject:@"your textfield value" forKey:@"your key name"];
    [[NSUserDefaults standardUserDefaults] synchronize];

获得价值:

NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"your key name"]);

确保您写相同的密钥名称。