2017-03-03 2 views
0

내 응용 프로그램에서 서버에 로그인하는 것과 같은 메커니즘을 사용합니다. 서버에 POST 사용자 자격 증명이 있습니다. 내 미래 API 호출. 질문 : 내 응용 프로그램의 모든 클래스간에이 토큰 (또는 기록 된 APIClient의 인스턴스)을 공유하는 방법은 무엇입니까?어떤 패턴이 모든 컨트롤러에 대해 공유 된 기록 된 ApiClient 인스턴스를 생성하는 데 가장 좋은 방법이 될까요?

이제 모든 컨트롤러 속성 "토큰"을 만들었고 각각의 세그먼트를 수행 할 때 너무 많은 보일러 코드 인 초기화해야하므로 솔루션을 다른 방법으로 공유하려고합니다. 감사합니다

+0

당신은 클래스와 정적 변수를 생성하고 바로 클래스 이름과 런타임에 알려진 것입니다 내가 토큰으로 정적 변수를 만들 수있는 방법 변수 –

+0

를 호출 할 수 있습니다 만 ? – zzheads

+0

토큰을 무엇을 의미합니까? API 호출에서 전달해야하는 문자열입니다. –

답변

1

내 응용 프로그램의 모든 클래스간에이 토큰 (또는 기록 된 APIClient의 인스턴스)을 공유하는 방법은 무엇입니까?

  • 만들기입니다 이는 shared instance -
    • 파괴 네트워크 요청
    • 에서 성공 토큰의 수신에 초기화가 보유하고있는 특성 (성공 토큰)이 더 이상 필요하지 않은 경우

일부 샘플 코드는이를 달성하기 위해 :

// APIHelper.h 

@interface APIHelper : NSObject 

@property (nonatomic) NSString *mySuccessToken; // can be any data type 

+ (instancetype)sharedInstance; 

@end 


// APIHelper.m 

@implementation APIHelper 

+ (instancetype)sharedInstance{ 
    static dispatch_once_t once; 
    static APIHelper *sharedInstance; 
    dispatch_once(&once, ^{ 
     sharedInstance = [self new]; 
    }); 
    return sharedInstance; 
} 

@end 


// Usage of the APIHelper shared instance 
// In the function responsible for firing the network request 


[MyFetchRequestWithSuccess:^{ 
    ... 

    [APIHelper sharedInstance].mySuccessToken = receivedSuccessToken; // update the shared instance with your received success token from the request  

} failure:^{ 
    ... 
}] 
관련 문제