【问题标题】:Fetch data using Post method in Objective-c在 Objective-c 中使用 Post 方法获取数据
【发布时间】:2015-09-30 06:34:00
【问题描述】:

我正在使用 POST 方法获取数据。我已经成功检索到所有数据。在 UI 中显示它需要很长时间,但我可以立即在控制台上打印它,我的代码是

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://www.xxxyyy.com/v1/api/client/authorize"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"ABCD" forHTTPHeaderField:@"Authkey"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

 NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) 
{
    NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

    [request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"Authkey"];

    NSData* data1 = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
    jsonReturnArray = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingAllowFragments error:&error];

    NSArray *array = [jsonReturnArray copy];
    [self rec:array];

    NSString *phoneNumber=[NSString stringWithFormat:@"%@",[jsonReturnArray valueForKey:@"phone"]];
    lblPhoneNumber.text = phoneNumber;

    NSString *Address=[NSString stringWithFormat:@"%@ %@ %@,CA %@",[jsonReturnArray valueForKey:@"street1"],[jsonReturnArray valueForKey:@"street2"],[jsonReturnArray valueForKey:@"city"],[jsonReturnArray valueForKey:@"postalcode"]];
    lblAddress.text=Address;//takes long time to display
    NSLog(@"%@",Address);//immeaditely print

    strlatitude=[jsonReturnArray valueForKey:@"latitude"];
    strlongitude=[jsonReturnArray valueForKey:@"longitude"];

    [self Map:(MKMapView *)mapLocation didUpdateUserLocation:(MKUserLocation *)nil];//method call
}] resume];

【问题讨论】:

  • 看到这个链接你的答案stackoverflow.com/questions/15749486/…
  • 我收到了所有数据,但显示我的问题需要很长时间
  • 从网络检索数据并将其显示在 UI 上需要多长时间。你能告诉我吗?
  • 它立即检索数据但需要1分钟才能显示它
  • 那么它可能是 UI 问题,而不是关于 POST 请求。它不应该花费时间(据我所知)

标签: ios xcode post http-post


【解决方案1】:

这太花时间来打印数据,但如果你使用 NSURLConnection 类,它可能会对你有所帮助。这是我的 Class 方法,它可能会有所帮助。

+ (void)postRequestData:(NSDictionary *)postVars
                 Action:(APIMode)action
  WithCompletionHandlar:(void (^) (id result, BOOL status))completionBlock
{

    NSURL *url = [NSURL URLWithString:API_URL([self getAPINameForType:action])];
    NSLog(@"Request URL %@",[NSString stringWithFormat:@"%@",url]);
    NSString *contentType = @"application/json";
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    NSError *err = nil;

    NSMutableDictionary *params=[[NSMutableDictionary alloc] initWithDictionary:postVars];
    //  [params setObject:[self getAPINameForType:action] forKey:@"mode"];
    NSLog(@"Paramater %@",params);

    NSData *body = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&err];
    [request setHTTPBody:body];
    [request addValue:[NSString stringWithFormat:@"%lu", (unsigned long)body.length] forHTTPHeaderField: @"Content-Length"];

    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
     {
         if(!connectionError)
         {
             NSError *error = nil;

             NSDictionary *dictResponse = [NSDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:data
                                                                                                                 options:NSJSONReadingAllowFragments error:&error]];

             dispatch_async(dispatch_get_main_queue(), ^{
                 completionBlock(dictResponse,(error == nil));
             });

             NSLog(@"%@",dictResponse);
         }
         else
         {
             dispatch_async(dispatch_get_main_queue(), ^{
                 completionBlock(connectionError.localizedDescription,NO);
             });
         }
     }];
}

使用这个方法代替它。它执行得很快,因为 NSURLConnection 类在后台执行。

【讨论】:

    【解决方案2】:

    尝试使用 NSURLConnection 类(手动代码)或简单地使用 AFNetworking 类(更少代码)来获取您的数据。 AFNetworking 内部使用 NSURLConnection 类本身。

    【讨论】:

    • 能否请你指导我一些关于上述代码的示例代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 2018-02-26
    • 1970-01-01
    相关资源
    最近更新 更多