【问题标题】:Getting data from a service Objective-C从服务获取数据 Objective-C
【发布时间】:2017-03-11 06:27:34
【问题描述】:

我是 iOS 新手,从以下服务数据显示数据时遇到问题

[{
    "Name": Rahul,
    "FatherName": Ravinder,
    "Designation": Engineering,
    "Profession": Software Eng,
    "Height": "5 ft 3 in",
    "Weight": "134.5 lbs"
}]

以下是我尝试过的代码。请帮我找出问题所在。提前致谢。

 NameDetails.m
---------------

- (void)viewDidLoad {
    [super viewDidLoad];
    [self callService:[appDelegate.signUpdata objectForKey:@"id"]];
}

-(void)callService:(NSString *)userid
{
    [Utility showIndicator:nil view1:self.view];
    JsonServicePostData = [[JsonServiceCls alloc] init];
    JsonServicePostData.delegate = self;
    [JsonServicePostData Getdata:userid];
}

-(void)DidFinishWebServicesPostData
{
    [Utility hideIndicator];

        NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
        _txtName.text=[dict objectForKey:@"Name"];
        _txtFName.text=[dict objectForKey:@"FatherName"];
        _txtDesg.text=[dict objectForKey:@"Designation"];
        _txtprof.text=[dict objectForKey:@"Profession"];
        _txtHeight.text=[dict objectForKey:@"Height"];
        _txtWeight.text=[dict objectForKey:@"Weight"];

    }

}

【问题讨论】:

  • “dict”如何从 api 获取数据?它只是在这里初始化,它没有任何数据。 “DidFinishWebServicesPostData”假设在这里从 API 返回一个 json。

标签: ios objective-c iphone xcode nsmutablearray


【解决方案1】:
+(void)makeHttpGETresponceParsingwithSerVer:(NSString *)strServer withCallBack:(void(^)(NSDictionary *dicArr,NSError *error))handler
{

NSURL *urlServer = [NSURL URLWithString:strServer];

    NSURLRequest *request = [NSURLRequest requestWithURL:urlServer];

    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

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


            handler(res,error);


    }];

    [postDataTask resume];
}
then call your method In viewDidLoad...

[RestClient makeHttpGETresponceParsingwithSerVer:@"YOUR_URL" withCallBack:^(NSDictionary *responceDic, NSError *error) {

    _txtName.text   =[responceDic objectForKey:@"Name"];
    _txtFName.text  =[responceDic objectForKey:@"FatherName"];
    _txtDesg.text   =[responceDic objectForKey:@"Designation"];
    _txtprof.text   =[responceDic objectForKey:@"Profession"];
    _txtHeight.text =[responceDic objectForKey:@"Height"];
    _txtWeight.text =[responceDic objectForKey:@"Weight"];

}];

// RestClient是类名,因为它是类方法,可以使用实例方法。

【讨论】:

    【解决方案2】:

    您好,对于这种 API 调用活动,更好的方法是使用 AFNetworking - https://github.com/AFNetworking/AFNetworking

    它非常简单且功能更强大。收到 json 响应后,您必须使用模型方法。

    #import <UIKit/UIKit.h>
    
    @interface NameDetails : NSObject
    
    @property (nonatomic, strong) NSString * designation;
    @property (nonatomic, strong) NSString * fatherName;
    @property (nonatomic, strong) NSString * height;
    @property (nonatomic, strong) NSString * name;
    @property (nonatomic, strong) NSString * profession;
    @property (nonatomic, strong) NSString * weight;
    
    -(instancetype)initWithDictionary:(NSDictionary *)dictionary;
    
    -(NSDictionary *)toDictionary;
    @end
    
    #import "RootClass.h"
    
    NSString *const kRootClassDesignation = @"Designation";
    NSString *const kRootClassFatherName = @"FatherName";
    NSString *const kRootClassHeight = @"Height";
    NSString *const kRootClassName = @"Name";
    NSString *const kRootClassProfession = @"Profession";
    NSString *const kRootClassWeight = @"Weight";
    
    @interface RootClass ()
    @end
    @implementation RootClass
    
    
    
    
    /**
     * Instantiate the instance using the passed dictionary values to set the properties values
     */
    
    -(instancetype)initWithDictionary:(NSDictionary *)dictionary
    {
        self = [super init];
        if(![dictionary[kRootClassDesignation] isKindOfClass:[NSNull class]]){
            self.designation = dictionary[kRootClassDesignation];
        }   
        if(![dictionary[kRootClassFatherName] isKindOfClass:[NSNull class]]){
            self.fatherName = dictionary[kRootClassFatherName];
        }   
        if(![dictionary[kRootClassHeight] isKindOfClass:[NSNull class]]){
            self.height = dictionary[kRootClassHeight];
        }   
        if(![dictionary[kRootClassName] isKindOfClass:[NSNull class]]){
            self.name = dictionary[kRootClassName];
        }   
        if(![dictionary[kRootClassProfession] isKindOfClass:[NSNull class]]){
            self.profession = dictionary[kRootClassProfession];
        }   
        if(![dictionary[kRootClassWeight] isKindOfClass:[NSNull class]]){
            self.weight = dictionary[kRootClassWeight];
        }   
        return self;
    }
    
    
    /**
     * Returns all the available property values in the form of NSDictionary object where the key is the approperiate json key and the value is the value of the corresponding property
     */
    -(NSDictionary *)toDictionary
    {
        NSMutableDictionary * dictionary = [NSMutableDictionary dictionary];
        if(self.designation != nil){
            dictionary[kRootClassDesignation] = self.designation;
        }
        if(self.fatherName != nil){
            dictionary[kRootClassFatherName] = self.fatherName;
        }
        if(self.height != nil){
            dictionary[kRootClassHeight] = self.height;
        }
        if(self.name != nil){
            dictionary[kRootClassName] = self.name;
        }
        if(self.profession != nil){
            dictionary[kRootClassProfession] = self.profession;
        }
        if(self.weight != nil){
            dictionary[kRootClassWeight] = self.weight;
        }
        return dictionary;
    
    }
    

    以上是Model Class。

    您的 JSON 看起来像一个数组。因此,您需要在其上迭代 Dictionary 值。除此之外,您可以直接传递它。

    现在在你的 ViewController 类中初始化可变数组

    然后像这样传递响应

    NSArray *arrayData = ResponseFromAFNETWORKING
    
        for (NSDictionary *data in arrayData) {
            NameDetails *modelFeed = [[NameDetails alloc] initFromDictinary:data]
           [self.YourMutableDictionary addObject:modelFeed]
    
        }
    self.updateDisplay:self.YourMutableDictionary[0] // If not array No iteration, you can prepare the model and pass it directly
    ----------------------------------------
    - (void)updateDisplay:(NameDetails *)feed {
        _txtName.text   =feed.Name;
        _txtFName.text  =feed.FatherName;
        _txtDesg.text   =feed.Designation;
        _txtprof.text   =feed.Profession;
        _txtHeight.text =feed.Height;
        _txtWeight.text =feed.Weight;
    
    }
    

    希望这会有所帮助。这是一种健壮且有弹性的方法,也是线程安全的机制

    【讨论】:

      猜你喜欢
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 2017-11-16
      • 2010-09-27
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多