gpt4 book ai didi

php - cocoa URL API : how can I return an error from the server *and* still download the data requested?

转载 作者:行者123 更新时间:2023-12-03 17:24:38 27 4
gpt4 key购买 nike

有趣的编程难题...

我未能将错误初始化为零,因此下面的代码崩溃了。

    NSString *query = [NSString stringWithFormat:@"http://mysite.com/getlatest.php?a=%@", aSuiteName];
NSURL *url = [NSURL URLWithString:query];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:10];
[request setHTTPMethod:@"GET"];
NSURLResponse *response = nil;
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ( !data || error != nil ) {
NSLog(@"Error downlading %@", error); //CRASH
return NO;
}

我的问题是,如何让我的服务器返回错误,以便 sendSynchronousRequest:returningResponse:error: 实际上收到错误,但仍继续下载数据?某种非 fatal error 会导致错误被初始化为 NSError 对象?

这与一个类似的难题有关,我之前想返回状态信息而不会完全失败。因此,虽然晦涩难懂,但我很想知道是否有一种技术可以实现这一点。

虽然这是一个Cocoa问题,但我认为答案将在php中。类似的东西

<?php

header( set 503 error here );

return data;

?>

最佳答案

我通过将数据包装到 NSError 对象中来处理这个问题。对于纯文本响应,我还使用响应作为本地化描述。我用单独的方法来评估结果是否成功。如果URL请求本身产生错误,我也认为是失败,并传递URL请求提供的NSError。

这是从我的 ServerRequest 类中截取的:

+ (NSError *) errorForStatusCode:(NSInteger) statusCode
contentType:(NSString *) contentType
textEncodingName:(NSString *) textEncodingName
data:(NSData *) data {

NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
if ([contentType isEqualToString:@"text/plain"]) {
[userInfo setValue:[[NSString alloc] initWithData:data encoding:[self stringEncodingForTextEncodingName:textEncodingName]]
forKey:NSLocalizedDescriptionKey];
} else if ( ... ) {
// handle other relevant types
}

return [NSError errorWithDomain:[[self class] description]
code:statusCode
userInfo:userInfo];
}

- (BOOL) statusCodeIndicatesSuccess:(NSInteger) statusCodeValue {
return 201 == statusCodeValue; // Modify this based on your API
}

- (BOOL) runSynchronouslyReturningResult:(NSData **) resultPtr error:(NSError **) errorPtr {
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:[self request] returningResponse:&response error:&error];
if (error) {
if (errorPtr) *errorPtr = error;
return NO;
}

self.statusCode = [response statusCode];
self.MIMEType = [response MIMEType];
self.textEncodingName = [response textEncodingName];
if ([self statusCodeIndicatesSuccess:self.statusCode]) {
if (resultPtr) *resultPtr = result;
return YES;
} else {
if (errorPtr) *errorPtr = [ServerRequest errorForStatusCode:self.statusCode
contentType:self.MIMEType
textEncodingName:self.textEncodingName
data:result];
if (resultPtr) *resultPtr = result;
return NO;
}
}

关于php - cocoa URL API : how can I return an error from the server *and* still download the data requested?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10656268/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com