如何在pdf中添加文字 iOS 在 URLByAppendingPathComponent 中添加自定义路径

(文章转载自:)
Swift调用Objcetive-C(4)&Swift学习笔记(31)&
//***************************************************
//& & & &&&&&&&Swift调用OC之文件操作1&&&&&&&
// ****&&本节内容&****
// 1.应用的目录结构
// 2.访问文件
// 3.NSURL和NSURLComponents
//***************************************************
import&Foundation
//***************************************************
// &&&&1.应用的目录结构:
// 1.MyApp.app -&这就是应用的运行目录/包(bundle),里面包含可执行文件和资源文件。AppStore购买应用后会安装到该目录
// 2.Documents -&用来存储用户产生的内容
// 3.Documents/Inbox -&用来访问被外部应用请求的当前应用的文件
// 4.Library -&用来存储非用户数据,比如配置文件.该目录对用户是不可见的,除了Caches子目录,其他都能通过iTunes备份
// 5.tmp -&用来存储那些下次重启不需要重新载入的临时信息,应用不运行时会自动清理.该目录内容也不会通过iTunes备份
// CommandLine是没有Bundle的,Application才有,下面涉及Bundle的操作都需要放到APP里面才能运行正确,比如放到viewDidLoad()方法内
//***************************************************
//**************************************
//****& & & & 2.访问文件& & & &*****
// &&可以使用String和NSURL来描述文件路径。官方推荐使用NSURL
// &&需要在Build Phases&&Target-Copy&&BundleResource里面添加了文件才能获取到文件路径
//**************************************
//使用String获取文件路径
if&let&filePath=&NSBundle.mainBundle().pathForResource("3001",ofType:&"jpg") {
& &&println("filePath=\(filePath)")&//Users/..../data/Containers/Bundle/Application/../TEST1.app/3001.jpg
//获取当前应用的临时文件目录(tmp)
let&tempDirectory101 =&NSTemporaryDirectory()
//获取当前用户域下的目录
//根据NSSearchPathDirectory参数确定查找哪个目录:Page184
//.DocumentDirectory - Documents目录
//.ApplicationDirectory - Applications目录
//根据NSSearchPathDomainMask的参数确定朝赵的文件系统域:Page185
//UserDomainMask-&用户域,指向当前用户的home目录(~) *这个最常用
let&directories101 =&NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask,&true)&//Users/EvaZis-Pro/Library/Containers/com.apple.dt.playground.stub.OSX.C01------C0ADA375--9DE5-AAAE/Data/Documents"
//**************************************
// & & & 3.NSURL和NSURLComponents
//**************************************
// URL结构
// scheme & : http (还有https、ftp、file、data等)
// host& & : blog.csdn.net
//path& & & : /qzidane
//&查询语句& :& viewmode=contents
//&等等....
//***************************************
//**********& & &&创建URL & & ************
//***************************************
//方法1:指定scheme/host/path
let&mutableURL201 =&NSURL(scheme:"Http", host:&"blog.csdn.net", path:&"/qzidane")
println(mutableURL201!)&//
let&emptyHostURL201 =&NSURL(scheme:"file", host:&nil, path:&"/TEST1/C01")
println(emptyHostURL201!)&//file:///TEST1/C01
let&emptyHostURL202 =&NSURL(scheme:"data", host:&nil, path:&"/TEST1/C01")
println(emptyHostURL202!)&//data:///TEST1/C01
//方法2:指定基础URL和相对URL
let&baseURL201 =&NSURL(string:"file:///TEST1/")
let&url201 =&NSURL(string:"C01/XX.html", relativeToURL:&baseURL201)&//file:///TEST1/C01/XX.html
let&absoluteURL201 =&url201?.absoluteURL& &//&file:///TEST1/C01/XX.html
let&absoluteURL202 =&url201?.absoluteString&//"file:///TEST1/C01/XX.html"
//注意对复杂的URL(比如说含有中文),需要进行UTF8编码转换,否则无法得到正确的URL
letcomplxString =&&""
let&complxURL1 =&NSURL(string:&complxString)&&//&这样得到的URL是nil
let&converString =&complxString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)//
let&complxURL2 =&NSURL(string:converString!)
//方法3:使用fileURLWithPath指定文件或目录的路径来得到URL
//其中isDirectory参数为true是返回一个目录(带"/"),false则不带"/"
let&path =&NSURL.fileURLWithPath("/Hello")&// Some&file:///Hello
let&pathDirectory =&NSURL.fileURLWithPath("/HeLLO",isDirectory:&true)!&//file:///HeLLO/
//***************************************
//**********&&获得URL指定部位& ************
//***************************************
let&url1 =&NSURL(string:&"")
url1?.host& & &//&
url1?.scheme& &&// https
url1?.port& & &// 99999
url1?.query&& &&// name=qqq
url1?.fragment&&// atat
url1?.lastPathComponent&// ttt
url1?.pathComponents&&&// "/", "haha","ttt"
url1?.path&& & & & & &&///haha/ttt
url1?.relativePath&& &&// /haha/ttt
let&url2 =&NSURL(string:&"")
url2?.user& & &// zidane
url2?.password&&// 1234
url2?.pathExtension&//png
//********************************
//**********&&文件URL& ************
//********************************
//检查资源是否可达:
//在获得文件URL后,使用URLForResource与checkResourceIsReachableAndReturnError,找到返回true,否则返回nil
let&fileURL =&NSBundle.mainBundle().URLForResource("3001", withExtension:&"jpg")
let&fileURLReachable =&fileURL?.checkResourceIsReachableAndReturnError(nil)
//判断是否为文件URL
let&webURL =&NSURL(string:&"")
webURL?.fileURL
fileURL?.fileURL
//路径拼接(修改路径)
let&modiURL =&NSURL(string:&"")
//增加文件或目录
let&URL1 =&modiURL?.URLByAppendingPathComponent("HiH.html")&//Some&
let&URL2 =&modiURL?.URLByAppendingPathComponent("DDD", isDirectory:&true)&//Some&
//增加后缀
let&URL3 =&modiURL?.URLByAppendingPathExtension("png")&//Some&
//删除最后一个路径/删除后缀
let&URL4 =&modiURL?.URLByDeletingLastPathComponent&& &&//Some&
let&URL5 =&URL3?.URLByDeletingPathExtension&& & & & &&//Some&
//*****************************************
//**********&NSURLComponents& ************
//&只支持IOS7.0及以上的API类,可与NSURL互相转换
//*****************************************
let&component =&NSURLComponents(string:&"")
//可以直接拼装和赋值:
component?.user&=&"Zidane"
component?.password&=&"Password1234"
component?.port&=&8888
component?.query&=&"toKey=1111"
component?.scheme&=&"https"
component?.fragment&=&"XO"
component?.path&=&"/中文/hey"
//结果如下:
component?.URL&&//
component?.percentEncodedPath&//"/%E4%B8%AD%E6%96%87/hey"
component?.path&//"/中文/hey"
component?.percentEncodedPassword
//component?....还有很多方法
阅读(...) 评论() &//***************************************************////&&& &&&&&&&Swift调用OC之文件操作-NSFileManager&&&&&&&//// ****&本节内容 ****//// 1.目录查询// 2.路径查询// 3.路径操作// & --创建目录// & --创建文件// & --拷贝/删除/移动文件/目录// & --获取文件访问权限////***************************************************&import Foundation&//====================================////*******&& NSFileManager & *********////====================================&//使用实例defaultManager()来处理文件操作let manager = NSFileManager.defaultManager()&//&&&&&&&&目录查询&&&&&&&&&&//获取目录有两个方法:URLsForDirectory和URLForDirectory//方法区别在于URLForDirectory还可以创建临时目录&//获得当前用户域下的Library/Application Support目录let urlsForDirectory =manager.URLsForDirectory(NSSearchPathDirectory.ApplicationSupportDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)&//file:///Users/.../Library/Containers/.../Data/Library/Application%20Support/&//获得当前用户域下Documents目录let urlForDirectory = manager.URLForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomain:NSSearchPathDomainMask.UserDomainMask,appropriateForURL:nil, create: true, error:nil)// file:///Users/.../Library/Containers/.../Data/Documents/&//&&&&&&&&路径查询&&&&&&&&&&&&&&&&&&// 1.浅搜索,只搜索当前目录层// & --方法1:contentsOfDirectoryAtPath// & --方法2:contentsOfDirectoryAtURL// & --区别在于方法1只返回文件和目录,方法2会把完整路径都返回// 2.深度遍历,遍历到子目录下的内容(符号链接不处理)// & --方法1:enumeratorAtPath// & --方法2:enumeratorAtURL//&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&let urlForDocument = manager.URLsForDirectory( NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask) //&let url = urlForDocument[0]asNSURLvar error: NSErrorPointer = nil&//浅搜索1:contentsOfDirectoryAtPathlet contentsOfPath_Shallow = manager.contentsOfDirectoryAtPath(url.path!,error:error)&//浅搜索2:contentsOfDirectoryAtURL//includingPropertiesForKeys参数是指特定条件,如创建时间let contentsOfURL_Shallow = manager.contentsOfDirectoryAtURL(url, includingPropertiesForKeys:nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles,error:error)&//深度遍历1:enumeratorAtPathlet contentsOfPath_Deep = manager.enumeratorAtPath(url.path!)println(contentsOfPath_Deep?.allObjects)&//[folder, folder/new.txt, text123.txt]&//深度遍历2:enumeratorAtURLlet contentsOfURL_Deep = manager.enumeratorAtURL(url,includingPropertiesForKeys:nil , options:NSDirectoryEnumerationOptions.SkipsHiddenFiles,errorHandler:nil)&&//&&&&&&&&& & 路径操作 &&&&&&&&&&&&//&// 1.创建目录:createDirectoryAtURL// 2.创建文件:createFileAtPath// & --将缓存NSData的数据写入成文件// 3.拷贝:copyItemAtPath////&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&//1.创建目录:createDirectoryAtURL//withIntermediateDirectories:true表示如果当前路径所指定的目录中父目录不存在,那么就连同父目录一起创建func createFolder(#FolderName: String, #BaseUrl: NSURL){& & let manager = NSFileManager.defaultManager()& & var error: NSErrorPointer= nil& & let folder = BaseUrl.URLByAppendingPathComponent(FolderName,isDirectory:true)& & println(&folder =/(folder)&)& & let exist = manager.fileExistsAtPath(folder.path!)& & if !exist {& & && let createSuccess = manager.createDirectoryAtURL(folder,withIntermediateDirectories:true,attributes: nil, error: error)& & && println(&createfolder success =/(createSuccess)&)& & }}&//2.创建文件:createFileAtPathfunc createFile(#FileName : String, #FileBaseUrl : NSURL){& & let manager = NSFileManager.defaultManager()& & var error : NSErrorPointer= nil& & let file = FileBaseUrl.URLByAppendingPathComponent(FileName)& & println(&file =/(file)&)& & let exist = manager.fileExistsAtPath(file.path!)& & if !exist {& & && let data = NSData(base64EncodedString:&aGVsbG8gd29ybGQ=&, options:.IgnoreUnknownCharacters)& & && let createSuccess = manager.createFileAtPath(file.path!,contents: data, attributes:nil)& & && println(&createfile success =/(createSuccess)&)& & }}&&//---------& 3.拷贝文件/目录& -----------//***方法:copyItemAtPath//---将指定路径下的一个文件(test.txt)拷贝到对应目录下另外一个文件(copyed.txt)//---将指定路径下的一个目录拷贝到对应目录//---当前进程要有读取srcURL的权限并且有toUrl的父级目录的写权限let urlForDocument1 = manager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask)let url1 = urlForDocument1[0]asNSURL//URLsForDirectory返回的是[AnyObject],所以要转换var error1: NSErrorPointer = nil&createFile(FileName: &test1.txt&,FileBaseUrl: url1)createFile(FileName: &folder&,FileBaseUrl: url1)createFile(FileName: &folder/new1.txt&,FileBaseUrl: url1)&let srcUrl = url1.URLByAppendingPathComponent(&test1.txt&)//换成folder则拷贝目录&let toUrl = url1.URLByAppendingPathComponent(&copyed.txt&)&let copyItemSuccess = manager.copyItemAtPath(srcUrl.path!, toPath:toUrl.path!, error:error) //返回BOOL&&&//---------& 4.删除文件/目录& -----------//***方法:removeItemAtURL//---当前进程要有toUrl的父级目录的写权限&let removeItemSuccess = manager.removeItemAtURL(toUrl,error:error)&&&//---------& 5.移动文件/目录& -----------//***方法:moveItemAtURL//---当前进程要有srcUrl和toUrl的父级目录的写权限&let moveItemSuccess = manager.moveItemAtURL(srcUrl,toURL:toUrl, error: error)&//---------& 6.文件访问权限& -----------let displayName = manager.displayNameAtPath(url.path!)&//返回本地化名:Documents&let file6 = url.URLByAppendingPathComponent(&copyed.txt&)//返回完整路径的Documents/test.txt&//获取权限属性let readable = manager.isReadableFileAtPath(file6.path!)& & & &//truelet writeable = manager.isWritableFileAtPath(file6.path!) & & &//truelet executable = manager.isExecutableFileAtPath(file6.path!)& &//falselet deleteable = manager.isDeletableFileAtPath(file6.path!) & &//true&//获取各种属性,比如创建时间,文件大小,文件类型等let attributes = manager.attributesOfItemAtPath(file6.path!, error:error)println(attributes!)/*[NSFileOwnerAccountID:501, NSFileSystemFileNumber: 3955613, NSFileExtensionHidden: 0,NSFileSystemNumber: , NSFileSize: 11, NSFileGroupOwnerAccountID: 20,NSFilePosixPermissions: 420, NSFileCreationDate:
14:03:19 +0000,NSFileType: NSFileTypeRegular, NSFileGroupOwnerAccountName: staff,NSFileReferenceCount: 1, NSFileModificationDate:
14:03:19 +0000]*/&&//获取内容数据:contentsAtPath//目录不正确或者获取错误则返回nillet data6 = manager.contentsAtPath(file6.path!)&&//比较文件/目录内文件是否相同let contentIsEqual = manager.contentsEqualAtPath(file6.path!, andPath:toUrl.path!)//true 都是test.txt
最新教程周点击榜
微信扫一扫NSTemporaryDirectory / NSItemReplacementDirectory / mktemp(3) - NSHipster
<meta content="NSTemporaryDirectory /NSItemReplacementDirectory /mktemp(3)" property="og:title"/>
外存被用于写入可持续化保存的数据,但当数据生命周期很短时,用Objective-C操作临时文件的资料却很少(可能有,不过这些资料本身也是“临时”的)。
临时文件的作用是在硬盘上简历buffer,既不会被原子化地转移到固定位置,也不会被某种合理的方式处理和销毁。需要找到文件系统上适当的位置、生成一个唯一的名字、再用完之后移动或删除文件的构思,才能去建立临时文件。
寻找依赖目录
建立临时文件(或目录)的第一步就是找到适当的不碍事的地方去写这些文件,而且这个地方也不会被Time Machine或iCloud之类的东西同步。
实际上,在Unix系统中, /tmp 目录是最佳选择了。但现如今的iOS和Max OS X应用都有了自己的沙箱容器,所以最好还是不要用hard-code的路径了。
NSTemporaryDirectory 是Foundation框架中的函数,这个函数会返回一个中相关系统上为写入临时文件而设计的目录。
近些年Apple把文件系统从那些调用 NSString 的地址的API中解放出来了,开发者改为用 NSURL 以及其上的API操作 NSFileManager 等类去解决这些问题。但这个解放并不是完全顺利的。
先看一看 NSTemporaryDirectory 的文档:
请查看 NSFileManager 的 URLForDirectory:inDomain:appropriateForURL:create:error: 方法来作为寻找临时目录的首选方法。
好吧,那看看NSFileManager -URLForDirectory:inDomain:appropriateForURL:create:error:方法里有什么:
你可以用这个方法去建立临时文件目录去存储类似自动保存的文件等。依此方法建立临时目录时用
NSItemReplacementDirectory 作为 directory 参数、 NSUserDomainMask 作为 domain参数、用一个合法的父级目录作为 url 参数传入。建立完成后,这个方法会返回该目录的URL。
这啥?读了好几遍我也没清楚怎么用。在邮件列表里找到遇到了同样的。
实际上,这个方法似乎是为配合 -replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: 方法移动现有临时文件到硬盘上的固定位置而设计的,并不是我们要找的东西。
这些关于 NSString 文件系统的变革整合太多太多了,我们还是直接看一些有用的东西吧:
[NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
生成唯一的目录名或文件名
找到了被(暂时)称作主目录的地方,下一步就是想办法去给临时文件命名。命名时除了文件名要唯一之外就没有什么好担心的事情了,这样做是为了不干预、也不被其他同名文件干扰。
生成唯一标示符的最佳办法是用 NSProcessInfo 的 globallyUniqueString 方法。
NSString *identifier = [[NSProcessInfo processInfo] globallyUniqueString];
这个方法会返回这种格式的字符串: 5BD255F4-CA55-4B82-A555-0F4BC5CA2AD6-479-D059CC
也有其他人建议直接调用系统的 mktemp(3) 命令去防止重名冲突。但是用 NSProcessInfo -globallyUniqueString 方法显然不像能产生冲突的样子。
还有个办法, NSUUID ()也可以生成出可用的结果,但我不觉得你会做出如此疯狂的事情来。
[[NSUUID UUID] UUIDString]
这个方法会返回这种格式的字符串: B-4C48-AEA6-C73BBEA17011
建立临时文件地址
用上述方法可以生成唯一标示符了,于是就能生成唯一名字的临时文件地址了:
NSString *fileName = [NSString stringWithFormat:@&%@_%@&, [[NSProcessInfo processInfo] globallyUniqueString], @&file.txt&];
NSURL *fileURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:fileName]];
建立临时目录
当一个程序需要生成很多临时文件时,建立子目录是一个好办法,可以帮助你简单快速地删除文件。
建立临时目录也是同样的方法调用 NSFileManager -createDirectoryAtURL:withIntermediateDirectories:attributes:error: :
NSURL *directoryURL = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]] isDirectory:YES];
[[NSFileManager defaultManager] createDirectoryAtURL:directoryURL withIntermediateDirectories:YES attributes:nil error:&error];
该目录的临时文件的地址要用 URLByAppendingPathComponent: 方法接上文件名:
NSURL *fileURL = [directoryURL URLByAppendingPathComponent:fileName];
向临时文件中写入内容
除非向文件中写入了内容或更新闻的时间戳,否则文件不会被建立。
NSData -writeToURL:options:error
Foundation库中有很多向硬盘写数据的方法,最直接的方法应该就是 NSData -writeToURL:options:error 了:
NSData *data = ...;
NSError *error = nil;
[data writeToURL:fileURL options:NSDataWritingAtomic error:&error];
NSOutputStream
更高级的API中比较常见的就是直接向数据流传入一个
NSOutputStream
实例。同样的,通过建立输出流来向临时文件地址写入和其他写入方法没什么两样:
NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:[fileURL absoluteString] append:NO];
最后一步就是让临时文件真正达到它临时的意义:清除。
虽然临时文件系统设计上没有说明临时文件在被系统自动删除前可以存在多久(至少最近没听到有人说过),但是你自己去管理好它是个很好的习惯。
用 NSFileManager -removeItemAtURL: 方法去删除临时文件或目录:
NSError *error = nil;
[[NSFileManager defaultManager] removeItemAtURL:fileURL error:&error];
“一切都会过去的!”这句谚语的意思就是所有的一切都是临时性的。在应用生命周期的上下文里,一些东西比其他的令具有临时性,所以我们应该为它们找到一个合理合适的地方去存放、保证唯一性、用过后不留痕迹。
或许我们可以从这个小小的应用生命周期中,学到一些关于我们短暂而灿烂的生命的意义。
() is the creator & maintainer of
and other popular , including ,
云游四海的工程师
下一篇文章
UIReferenceLibraryViewController /DCSDictionaryRef
虽然字典的地位很大程度上已经被基于网络的“一键释义”功能所替代,但是字典和词汇表在拼写检查、语法检查、自动纠错、自动摘要、语义分析等领域,仍然在幕后扮演着重要角色。
除非另有声明、本网站采用知识共享「」许可协议授权。
本站文章由
Lin Xiangyu
Sheldon Huang
Yifan Xiao

我要回帖

更多关于 如何在pdf中添加图片 的文章

 

随机推荐