1

我是 Objective-C 的新手,正在阅读《The Big Nerd Ranch Guide to Objective-C Programming》一书。

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSURL *url = [NSURL URLWithString:@"http://www.google.com/imagess/logos/ps_logo2.png"];

        NSURLRequest *request = [NSURLRequest requestWithURL:url];

        NSError *error =nil;

        NSData *data = [NSURLConnection sendSynchronousRequest:request
                                             returningResponse:NULL
                                                         error:&error];



        if(!data){
            NSLog(@"fetch failed %@", [error localizedDescription]);
            return 1;
        }

        NSLog(@"the files is %lu bytes", [data length]);

        BOOL written = [data writeToFile:@"/tmp/google.png"
                                 options:NSDataWritingAtomic
                                   error:&error];

        if(!written){
            NSLog(@"write failed: %@",[error localizedDescription]);
            return 1;
        }
        NSLog(@"Success!");

        NSData *readData = [NSData dataWithContentsOfFile:@"/tmp/google.png"];
        NSLog(@"the file read from disk has %lu bytes", [readData length]);

    }
    return 0;
}

问题是这样的,如果我将 *url 更改为http://aFakeDomain.com/imimimi/myImage.png那么我的数据对象将为零,因为没有主机并且一切正常.. 但是如果我使用 google 作为域并指向错误的文件位置,然后数据对象仍然具有标头信息并且不是零,因此我永远不会得到我应该的错误。

确保 *url 成功找到文件的最佳方法是什么。

谢谢

4

3 回答 3

3

您需要将响应传递给NSURLConnection调用,然后检查其状态代码:

NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSData *data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&httpResponse
                                                     error:&error];
int code = [httpResponse statusCode];

你会404在你的情况下得到一个状态码。

于 2013-01-28T18:47:27.667 回答
2
NSUrlResponce *responce = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&responce
                                                     error:&error];

if (error) {
    // handle the error
}

if (![[responce MIMEType] isEqualToString:@"image/png"]) {
    // failed to get png file
}
于 2013-01-28T18:52:49.527 回答
0

文件名也有一些错误;而不是@"/tmp/google.png",你应该使用代码列表:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"google.png"];
于 2013-01-29T02:28:12.913 回答