码农的日常之iOS开发iOS 开发IT梦之队

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

2016-08-05  本文已影响2973人  rztime

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]);
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读