iOS 通过url获取网络文件、图片的信息(文件大小)

GetURLFileLength.h 文件


/**
 *  @brief 通过网络url获得文件的大小
 */
@interface GetURLFileLength : NSObject<NSURLConnectionDataDelegate>

typedef void(^FileLength)(long long length, NSError *error);

@property (nonatomic, copy) FileLength block;

/**
 *  通过url获得网络的文件的大小 返回byte
 *
 *  @param url 网络url
 *
 *  @return 文件的大小 byte
 */
- (void)getUrlFileLength:(NSString *)url withResultBlock:(FileLength)block;

GetURLFileLength.m 文件

@implementation GetURLFileLength

/**
 *  通过url获得网络的文件的大小 返回byte
 *
 *  @param url 网络url
 *
 *  @return 文件的大小 byte
 */
- (void)getUrlFileLength:(NSString *)url withResultBlock:(FileLength)block
{
    _block = block;
    NSMutableURLRequest *mURLRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [mURLRequest setHTTPMethod:@"HEAD"];
    mURLRequest.timeoutInterval = 5.0;
    NSURLConnection *URLConnection = [NSURLConnection connectionWithRequest:mURLRequest delegate:self];
    [URLConnection start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSDictionary *dict = [(NSHTTPURLResponse *)response allHeaderFields];
    NSNumber *length = [dict objectForKey:@"Content-Length"];
    [connection cancel];
    if (_block) {
        _block([length longLongValue], nil);    // length单位是byte,除以1000后是KB(文件的大小计算好像都是1000,而不是1024),
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"获取文件大小失败:%@",error);
    if (_block) {
        _block(0, error);
    }
    [connection cancel];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

当中获得到头信息中 dict包含的信息可以通过解析获得,打印的dict内容如下:

Printing description of dict:
{
    "Accept-Ranges" = bytes;
    "Access-Control-Allow-Origin" = "*";
    "Access-Control-Expose-Headers" = "X-Log, X-Reqid";
    "Access-Control-Max-Age" = 2592000;
    Age = 1;
    "Cache-Control" = "public, max-age=31536000";
    Connection = "keep-alive";
    "Content-Disposition" = "inline; filename=\"4587945932505.mp4\"";
    "Content-Length" = 1149810;  // 文件的大小
    "Content-Transfer-Encoding" = binary;
    "Content-Type" = "video/mp4"; // 文件的类型
    Date = "Fri, 05 Aug 2016 01:55:16 GMT";
    Etag = "\"Fo5QDSpIMMLcV2W2fH899FH4q********\"";
    "Last-Modified" = "Fri, 22 Jul 2016 01:46:05 GMT"; // 最近一次修改时间
    Server = nginx;
    "X-Log" = "mc.g;IO:2";
    "X-Qiniu-Zone" = 0;
    "X-Reqid" = vHoAANGi1Q6OxmcU;
    "X-Via" = "1.1 suydong34:0 (Cdn Cache Server V2.0), 1.1 yd70:4 (Cdn Cache Server V2.0)";
}

如果要获取本地文件的文件的信息(文件大小),同样可以在GetURLFileLength.h 文件中

/**
 *  通过文件的名字以及创建的时间获得文件的大小 返回byte
 *
 *  @param fileName 文件名字 
 *  @param created  文件在服务器的创建时间   通过创建的时间建立的目录文件
 *  @param block length:文件长度, status:是否已经下载 返回 已下载,未下载
 *  @return
 */
- (void)getLocalPathFileLength:(NSString *)fileName created:(UInt32)created withResultBlock:(void(^)(long long length, NSString *status))block;

GetURLFileLength.m 文件

- (void)getLocalPathFileLength:(NSString *)fileName created:(UInt32)created withResultBlock:(void(^)(long long length, NSString *status))block
{
    // 判断是否已经离线下载了
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
// filepath是通过一定的方式拼接的,我的文件一般存在于documents下的LOCAL_SAVE_PATH当中,然后以created作为文件的目录保存,所以完整的路径拼接即如下:
    NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%d/%@", LOCAL_SAVE_PATH, created, fileName]];
    
    NSFileManager *filemanager = [NSFileManager defaultManager];
    
    if ([filemanager fileExistsAtPath:path]) {
        long long length = [[filemanager attributesOfItemAtPath:path error:nil] fileSize];
        if (block) {
            block(length, @"已下载");
        }
    } else {
        if (block) {
            block(0, @"未下载");
        }
    }
}

其他信息也可以如下获取

/**
 *  通过文件的路径获得本地文件的基本信息
 *
 *  @param filePath <#filePath description#>
 *  @param block    <#block description#>
 */
- (void)getFileInfoByFilePath:(NSString *)filePath WithBlock:(void(^)(long long fileSize, NSDate *modificationtime, NSError *error))block
{

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error = nil;
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:filePath error:&error];
    
    if (fileAttributes != nil) {
        NSNumber *fileSize = [fileAttributes objectForKey:NSFileSize];
        NSDate *fileModDate = [fileAttributes objectForKey:NSFileModificationDate]; // 最近一次的修改时间

        if (block) {
            block([fileSize unsignedLongLongValue], fileModDate, nil);
        }
    } else {
        if (block) {
            block(0, nil, [NSError errorWithDomain:@"文件路径出错" code:100 userInfo:nil]);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,366评论 25 709
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 12,257评论 2 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,246评论 19 139
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 11,290评论 6 13
  • 清晨的第一声鸟鸣像一颗新生的星辰发出的第一缕光线从千百万年前赶来(那里,第一只鸟刚刚形成叫出了第一声)
    诗人凤凰阅读 230评论 0 1