我想通过NSURL检查我的服务器上是否存在文件并且感谢NSURLSession(可能不是最佳解决方案?)。为此,我执行了以下几行:
ViewControllerB中使用的方法:
- (void)testFichierExiste:(void(^)(int intTest))retourErreur atURL:(NSURL *)cheminTest {
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:cheminTest];
request.HTTPMethod = @"HEAD";
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if (statusCode == 200 || statusCode == 403) { //file exists
dispatch_async(dispatch_get_main_queue(), ^{
retourErreur(1); //Send "1" to my ViewControllerA to say file exists
});
}
}];
[task resume];
从ViewControllerA调用的方法:
__block int fileExist = 0;
[[[ViewControllerB alloc] init] testFichierExiste:^(int retourSession) {
fileExist = retourSession; //doesn't work
} atURL:nbComptes]; //nbComptes = same path as cheminTest in ViewControllerB
在我的ViewControllerA上,我得到了结果" 1"当文件存在时," nil"当它与retourSession
的值相反时。
但是要释放块testFichierExiste:^(int retourSession)
,我需要将retourSession
的值影响到另一个int变量fileExist
。
但这种价值转移并不奏效,我不知道为什么:
2018-04-18 18:34:28.978024+0200 AppTest[3284:76369] fileExist value: 0
2018-04-18 18:34:29.142198+0200 AppTest[3284:76369] retourSession value: 1
我想也许是因为两个变量之间的类别不同而存在问题? 问候。
答案 0 :(得分:0)
根据您对文件是否存在的信息的处理,您需要等待请求完成并且回执已执行。
我想您尝试做的是更新fileExist
var并根据其值更新一些UI。
__block int fileExist = 0;
[[[ViewControllerB alloc] init] testFichierExiste:^(int retourSession) {
fileExist = retourSession; //doesn't work
} atURL:nbComptes]; //nbComptes = same path as cheminTest in ViewControllerB
// you probably have some code here testing fileExist
这不会起作用,因为你从不等待回调。也许您可以通过在视图控制器上使用基于该回调结果更新UI的方法来解决您的问题。
ViewControllerB *vcB = [[ViewControllerB alloc] init];
[vcB testFichierExiste:^(int retourSession) {
[vcB updateUIForExistenceOfFile:retourSession];
} atURL:nbComptes];
- (void)updateUIForExistenceOfFile:(int)fileExist {
// update your UI
}