NSURL播放沙盒资源

2017-05-15  本文已影响0人  ashura_

遇到的问题

有时候要下载mp4,mp3等文件在沙盒下,通过播放器播放时候,无法播放,当资源在bundle下或者网上url时候能够正常播放,在沙盒下则没播放出来。
代码如下:
Bundle获取地址:

NSURL *bundleUrl = [[NSBundle mainBundle] URLForResource:@"1" withExtension:@"mp4"];
NSLog(@"bundle地址:%@",bundleUrl);

网络地址:

NSURL *videoUrl = [NSURL URLWithString:@"http://v.jxvdy.com/sendfile/DVVpy3JGQjjW02dR8N4SNJ4ZwDVREoa0GKsxcaL0qIX2ouTmQgKUS1p7XxxuZLE9-vS--xl7-eQvyCW-hvUvDKIu-HKRzw"];
NSLog(@"网络地址:%@",videoUrl);

沙盒地址

NSString *strPath = [NSString stringWithFormat:@"%@/Documents/1.mp4",NSHomeDirectory()];
NSLog(@"strPath:%@",strPath);
 NSURL *sandbox1Url = [NSURL URLWithString:strPath];
NSLog(@"沙盒地址1:%@",sandbox1Url);

日志输出为:

经过日志分析:
使用沙盒地址跟网络地址,bundle地址明显缺失一个scheme,这就是问题所在。

    NSString *strPath = [NSString stringWithFormat:@"%@/Documents/1.mp4",NSHomeDirectory()];
    NSLog(@"strPath:%@",strPath);
    NSURL *sandboxUrl = [NSURL fileURLWithPath:strPath];

问题在于fileURLWithPathURLWithString的区别,根本原因在于对URL的理解,摘抄Apple Documents

NSURL简介

An NSURL object represents a URL that can potentially contain the location of a resource on a remote server, the path of a local file on disk, or even an arbitrary piece of encoded data.
Structure of a URL
An NSURL object is composed of two parts—a potentially nil base URL and a string that is resolved relative to the base URL. An NSURL object is considered absolute if its string part is fully resolved without a base; all other URLs are considered relative.

For example, when constructing an NSURL object, you might specify file:///path/to/user/ as the base URL and folder/file.html as the string part, as follows:

NSURL *baseURL = [NSURL fileURLWithString:@"file:///path/to/user/"];
NSURL *URL = [NSURL URLWithString:@"folder/file.html" relativeToURL:baseURL];
NSLog(@"absoluteURL = %@", [URL absoluteURL]);

When fully resolved, the absolute URL is file:///path/to/user/folder/file.html.

A URL can be also be divided into pieces based on its structure. For example, the URL https://johnny:p4ssw0rd@www.example.com:443/script.ext;param=value?query=value#ref contains the following URL components:

Component Value
scheme https
user johnny
password p4ssw0rd
host www.example.com
port 443
path /script.ext
pathExtension ext
pathComponents ["/", "script.ext"]
parameterString param=value
query query=value
fragment ref

The NSURL class provides properties that let you examine each of these components.

fileURLWithPathURLWithString的区别

其实两个Select都是返回一个Url,不同的是fileURLWithPath用在本地资源,而URLWithString更多的用在远程资源。最根本的原因是URL不能缺少scheme
这次使用出错的原因,也许是我们经常使用http请求接口或者图片:

 NSURL *url = [NSURL URLWithString:@"www.baidu.com"];
 NSURLRequest *request = [NSURLRequest requestWithURL:url];

习惯性的用到URLWithString来生成NSUrl

上一篇下一篇

猜你喜欢

热点阅读