0

Objective-C 项目中用 AFNetworking 框架网络请求错误时,返回NSError类型的error ,可以通过error.code直接获取网络请求错误代码,如下面的-1022

swift 项目中使用 AFNetworking 框架网络请求错误时,返回的是Error类型的error,没有error.code去获取请求错误的代码,但是打印出的error中有错误的代码,该如何获取?

以下代码分别为OC项目和Swift项目中用AFNetworking框架请求网络图片的代码。
1、别吐槽我不用SDWebImage框架,我只是用来测试一下下。
2、代码没有问题,只是App Transport Security没有设置导致的错误。

    NSURL *url = [NSURL URLWithString:@"http://img4.imgtn.bdimg.com/it/u=1001032158,3871637906&fm=11&gp=0.jpg"];

    [self.imageView setImageWithURLRequest:[NSURLRequest requestWithURL:url] placeholderImage:nil success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
        
        self.imageView.image = image;
        
    } failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
        
        printf("NSError.code = %ld", (long)error.code);
        
    }];

打印出的结果是: NSError.code = -1022

        let url = URL.init(string: "http://img4.imgtn.bdimg.com/it/u=1001032158,3871637906&fm=11&gp=0.jpg")
        let request = URLRequest(url: url!)
        
        imageView.setImageWith(request, placeholderImage: UIImage.init(named: "image"), success: { (request: URLRequest, response: HTTPURLResponse?, image: UIImage) in
            
            self.imageView.image = image
            
        }) { (request: URLRequest, response: HTTPURLResponse?, error:Error) in
            
            print("图片加载失败:\(error)")
        }

打印出的结果是:图片加载失败:Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo= ......

2016-09-27 提问

1 个回答

2

let code = (error as! NSError).code

推广链接