![](/img/trans.png)
[英]UIApplication delegate must be used from main thread only - Swift
[英]WARNING-[UIApplication delegate] must be used from main thread only
我收到警告 [UIApplication delegate] must be used from main thread only in the below line of code
((AppDelegate *)[[UIApplication sharedApplication] delegate]).loginProfile.accessToken;
以下是我的代码。
+ (NSString *)accessTokenHashForDate:(NSDate *)date withParameters:(NSArray *)params{
NSString *accessToken = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).loginProfile.accessToken;
NSString *paramsStr = [params componentsJoinedByString:@""];
NSString *hashStr = [NSString stringWithFormat:@"%@%@%@%@", [CommonUtil IMEI], [date agileHashFormattedString], (!paramsStr) ? @"" : paramsStr, accessToken];
return hashStr
}
谁能告诉我如何删除这个警告信息?
您必须通过放入下面的代码块在主线程中运行此代码,
dispatch_async(dispatch_get_main_queue(), ^{
// Put your code here
})
你可以像这样使用这个块,
+ (NSString *)accessTokenHashForDate:(NSDate *)date withParameters:(NSArray *)params{
NSString *hashStr = @"";
dispatch_async(dispatch_get_main_queue(), ^{
NSString *accessToken = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).loginProfile.accessToken;
NSString *paramsStr = [params componentsJoinedByString:@""];
hashStr = [NSString stringWithFormat:@"%@%@%@%@", [CommonUtil IMEI], [date agileHashFormattedString], (!paramsStr) ? @"" : paramsStr, accessToken];
});
return hashStr;
}
或者在dispatch_async
块中调用accessTokenHashForDate
function。
dispatch_async(dispatch_get_main_queue(), ^{
// Call Function here
});
+ (NSString *)accessTokenHashForDate:(NSDate *)date withParameters:(NSArray *)params{
__block NSString *accessToken = NULL;
if ([NSThread isMainThread]) {
accessToken = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).loginProfile.accessToken;
} else {
dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_async(dispatch_get_main_queue(), ^{
accessToken = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).loginProfile.accessToken;
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_semaphore_signal(semaphore);
}
NSString *paramsStr = [params componentsJoinedByString:@""];
NSString *hashStr = [NSString stringWithFormat:@"%@%@%@%@", [CommonUtil IMEI], [date agileHashFormattedString], (!paramsStr) ? @"" : paramsStr, accessToken];
return hashStr;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.