检查坏NSURLConnection

时间:2013-01-28 17:25:18

标签: objective-c nsurlconnection nsdata

我是Objective-C的新手,并阅读了“The Big Nerd Ranch Objective-C编程指南”一书。

#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,那么我的数据对象将是nill,因为没有主机,一切正常......但如果我使用谷歌作为域并指向一个错误的文件位置然后数据对象stil有头信息,并且不是零,因此我永远不会得到我应该的错误。

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

感谢

3 个答案:

答案 0 :(得分:3)

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

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

您的案件中会收到404状态代码。

答案 1 :(得分: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
}

答案 2 :(得分:0)

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

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"google.png"];