Data from the API call does not fill within the method

综合技术 2018-02-14

I decided to go with an embedded API call within a view controller, and I'm having trouble with the data reaching out before the API returns with the information.

How do I wait for the data to be returned before the view controller displays all the values as nulls?

Thanks for any help.

#import "BDChangeApproveController.h"
#import "BDItemChangeDetailAPI.h"

@interface BDChangeApproveController () 

@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic, copy) NSArray *APIItem;

@end

@implementation BDChangeApproveController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
}

- (void)fetchFeedAPIChangeDetail
{

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:config
                                         delegate:nil
                                    delegateQueue:nil];

NSString *requestString = @"http://URL.com";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];

NSURLSessionDataTask *dataTask =
[self.session dataTaskWithRequest:req
                completionHandler:
 ^(NSData *data, NSURLResponse *response, NSError *error){

     NSDictionary *jsonObject1 = [NSJSONSerialization JSONObjectWithData:data
                                                                 options:0
                                                                   error:nil];
     //NSLog(@"%@", jsonObject1);
     self.APIItem = jsonObject1[@"CoDetail"];
     NSLog(@"%@", self.APIItem);

 }];

[dataTask resume];

}

//API authentication

- (void)  URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler
{
NSURLCredential *cred =
[NSURLCredential credentialWithUser:@"demouser"
                           password:@"secret"
                        persistence:NSURLCredentialPersistenceForSession];
completionHandler(NSURLSessionAuthChallengeUseCredential, cred);
}

- (void)viewDidLoad
{

[super viewDidLoad];
[self fetchFeedAPIChangeDetail];
self.title = @"Action";
self.coNumberLabel.text = self.itemAPI.changeOrder;
//self.recipeImageView.image = [UIImage imageNamed:self.recipe.image];

NSLog(@"testtttt");

NSMutableString *coDetailsText = [NSMutableString string];
coDetailsText =
 [[NSMutableString alloc] initWithFormat:@"Review Change Order details bellown====================n%@ n================== nPlanned Start %@n==================nSubcategory: %@n==================nService: %@n==================nAssociated CIs: %@n==================nEnvironment CI: %@n==================nApproval Group: %@n==================nInitiator : %@n==================nCoordinator : %@n==================nRisk Level : %@n==================nPerforming Group : %@n==================nImplementation Plan : %@n==================nStatus : %@n==================nRecovery Plan : %@n==================n",

 /*
 self.item.title,
 self.item.changeOrder,
 self.item.subcategory,
 self.item.assignmentGroup,
 self.item.changeOrder,
 self.item.subcategory,
 self.item.assignmentGroup,
 self.item.approverEid,
 self.item.approverEid,
 self.item.subcategory,
 self.item.assignmentGroup,
 self.item.title,
 self.item.title,
 self.item.title
 */

 self.itemAPI.title,
 self.itemAPI.plannedStart,
 self.itemAPI.subcategory,
 self.itemAPI.service,
 self.itemAPI.associatedCi,
 self.itemAPI.environment,
 self.itemAPI.assignmentGroup,
 self.itemAPI.initiator,
 self.itemAPI.coordinator,
 self.itemAPI.riskLevel,
 self.itemAPI.performingGroup,
 self.itemAPI.implementationPlan,
 self.itemAPI.status,
 self.itemAPI.recoveryScope

// self.item.valueInDollars,
// self.item.dateCreated,
// self.item.subcategory,
// self.item.service,
// self.item.associatedCIs,
// self.item.environment,
// self.item.approvalGroup,
// self.item.initiator,
// self.item.coordinator,
// self.item.riskLevel,
// self.item.performingGroup,
// self.item.implementationPlan,
// self.item.validationPlan,
 //self.item.recoveryScope

 ];

self.coDetailsTextView.text = coDetailsText;
NSLog(@"overrrr");

}

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

@end

// Adding File

#import 
#import "BDItemChangeDetailAPI.h"

@interface BDChangeApproveController : UIViewController

@property (weak, nonatomic) IBOutlet UILabel *coNumberLabel;
@property (weak, nonatomic) IBOutlet UITextView *coDetailsTextView;

@property (nonatomic, strong) BDItemChangeDetailAPI *itemAPI;

@end

Looks like you're doing something asynchronously and expecting it to act synchronously.

Look at the below piece of code you're using in viewDidLoad:

[self fetchFeedAPIChangeDetail]; // this takes some time to complete
self.title = @"Action"; // this happens immediately after the above starts, not ends
self.coNumberLabel.text = self.itemAPI.changeOrder; // so does this, so at this point itemAPI is probably nil

fetchFeedAPICheckDetail is an asynchronous process, so it might take a few seconds to complete, whereas setting the title and coNumberLabel happens immediately after, so you don't yet have the itemAPI information from the URL Session. Your code doesn't wait for fetchFeedAPIChangeDetail to be done with the request before continuing onto the next line.

Hello, buddy!

责编内容by:Hello, buddy! (源链)。感谢您的支持!

您可能感兴趣的

有货iOS数据非侵入式自动采集探索实践... 随着有货APP的不断迭代开发,数据和业务部门对于客户端用户行为数据的需求越来越多;为了更好的监控APP使用的状况,客户端团队对于APP自身的运行的数据需求也愈发迫切。迫切地需要一套客户端数据采集的工具...
iOS Flexbox 布局优化 Frame AutoLayout iOS 开发中给系统给我们提供了两种布局,frame 布局 和 AutoLayout 布局,虽然frame布局性能很高 但面对现在越来越丰富的iPhon...
0-学习查阅API资料的重要性及怎样学 说起来我的编程学习经历,我自己都不知道该怎么感慨了。直到我现在基本以python3为主,R为辅的状态之前,我经历但没有学透过的有:vb,c++(mql4),java,matlab......编程语言各...
NotePlan Calendar + Markdown + Notes Comes to iOS When I first heard about NotePlan , I was intrigued. It was a Mac app that used a text form...
iOS 如何优雅地 hook 系统的 delegate 方法?... 在 iOS 开发中我们经常需要去 hook 系统方法,来满足一些特定的应用场景。 比如使用 Swizzling 来实现一些 AOP 的日志功能,比较常见的例子是 hook UIViewCo...