在 mac 上如何使用 xcode, swift 语言开发一个向 ftp 服务器上传文件的工具?
使用的是第三方库 Rebekka,下载地址为:https://github.com/Constantine-Fry/rebekka。下载完之后直接将所有的 swift 文件拷到项目中即可使用。
下面是我自己写的代码 ,首先是 FtpManager.swift 类,封装了上传文件和创建文件夹的方法,代码如下:
//
// FtpHelper.swift
// MacFtpUploader
//
// Created by Jie Tian on 23/3/16.
// Copyright © 2016 Jie Tian. All rights reserved.
// import Foundation public class FtpManager
{
let m_host:String;
let m_username:String;
let m_password:String;
let m_session:Session; init (host:String,username:String,password:String,passive:Bool)
{
m_host=host;
m_username=username;
m_password=password; var config=SessionConfiguration();
config.host=host;
config.username=username;
config.password=password;
config.passive=passive; m_session=Session(configuration: config);
} public func UploadFile(srcPath:String,tarPath:String,callback:(Bool) -> Void)
{
let localPath=NSURL(fileURLWithPath: srcPath); m_session.upload(localPath, path: tarPath)
{
(succeed,error) -> Void in
let fullUrl=self.m_host+tarPath;
if succeed
{
print("Upload succeed!\nSource path: \(localPath)\nTarget url: \(fullUrl)\n");
}
else
{
print("Upload failed...\nError: \(error)\nSource path: \(localPath)\nTarget url: \(fullUrl)\n");
} callback(succeed);
};
} public func CreateDirectory(path:String)
{
m_session.createDirectory(path)
{
(succeed, error) -> Void in
let url=self.m_host+path;
if succeed
{
print("Create directory succeed!\nUrl: \(url)\n");
}
}
}
}
FtpManager.swift
下面是程序的入口 main.swift,代码如下:
//
// main.swift
// MacFtpUploader
//
// Created by Jie Tian on 22/3/16.
// Copyright © 2016 Jie Tian. All rights reserved.
// import Foundation // 获取 host 所对应的文件夹的 url
func GetHostDirUrls(host:String,inout rootHost:String) -> [String]
{
var urls=[String]();
let words=host.characters.split("/");
let w0Str=String(words[]);
let w1Str=String(words[]);
rootHost="\(w0Str)//\(w1Str)"; for i in ..<words.count
{
var url:String=String();
for t in ...i
{
url+="/"+String(words[t]);
}
urls.append(url);
} return urls;
} // 传入一个根文件夹路径,取得其所有的文件与文件夹路径
func GetAllFiles(rootDir:String,inout allDirectories:[String],localRootDirName:String) -> [String]
{
let manager=NSFileManager.defaultManager();
let url=NSURL(fileURLWithPath: rootDir);
let contents=manager.enumeratorAtURL(url, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil); var allFiles=[String]();
allDirectories=[localRootDirName]; // local root dir name must be created first for item in contents!
{
var isDir:ObjCBool=ObjCBool(false);
let exists=manager.fileExistsAtPath(item.path, isDirectory:&isDir);
if !exists
{
continue;
} if isDir
{
allDirectories.append(item.path);
}
else
{
allFiles.append(item.path);
}
} return allFiles;
} // 将本地的路径转化为上传的 url
func GetUrl(path:String,absolutePath:String,localRootDirName:String) -> String
{
// 获取 “IOS” 的位置
var rightIndex:String.Index? = nil; for i in ..<path.characters.count
{
if i+localRootDirName.characters.count > path.characters.count
{
continue;
} var isRight:Bool=true; for k in ..<localRootDirName.characters.count
{
let c = path[path.startIndex.advancedBy(i+k)];
let tc = localRootDirName[localRootDirName.startIndex.advancedBy(k)];
if c != tc
{
isRight = false;
break;
}
} if isRight
{
rightIndex = path.startIndex.advancedBy(i);
break;
}
} // 拼接 url
return absolutePath+"/"+path.substringFromIndex(rightIndex!);
} func Upload(host:String,username:String,password:String,path:String,passive:Bool)
{
print("Start upload:\nhost: \(host)\nusername: \(username)\npassword: \(password)\npath: \(path)\npassive: \(passive)\n"); // 创建host对应的文件夹
var rootHost:String=String();
let hostDirUrls=GetHostDirUrls(host,rootHost:&rootHost);
let ftp=FtpManager(host:rootHost,username:username,password:password,passive: passive); for hu in hostDirUrls
{
ftp.CreateDirectory(hu);
} let pathDirs=path.characters.split("/");
let localRootDirName = String(pathDirs.last!);
var allDirs:[String]=[String]();
let allFiles=GetAllFiles(path, allDirectories: &allDirs,localRootDirName:localRootDirName); // 创建本地文件需要的文件夹
for dp in allDirs
{
let dirUrl=GetUrl(dp,absolutePath: hostDirUrls.last!,localRootDirName:localRootDirName);
ftp.CreateDirectory(dirUrl);
} // 上传文件
let totalCount=allFiles.count;
var uploadedCount=; for fp in allFiles
{
let fileUrl=GetUrl(fp,absolutePath: hostDirUrls.last!,localRootDirName:localRootDirName);
ftp.UploadFile(fp, tarPath: fileUrl)
{
(succeed) -> Void in
if succeed
{
uploadedCount++; if uploadedCount >= totalCount
{
print("\nAll files are uploaded to [\(host)] succeed!!!\n");
}
}
}
}
} // 程序入口
func Main()
{
// let host="ftp://119.15.139.103/TianJie";
// let username="feixiang.tu";
// let password="feixiang.tu";
// let path="/Users/jie.tian/Documents/BleachMaster/FtpBackup/IOS/"; // let host="ftp://54.223.59.161/Tian/Jie/";
// let username="bleach";
// let password="8c%2rFnlCh&*7$TQqx#UikX";
// let path="/Users/jie.tian/Documents/BleachMaster/FtpBackup/IOS/"; // get arguments first
let argFilePath=NSBundle.mainBundle().bundlePath+"/MacFtpUploader_Arguments";
let argFileUrl=NSURL(fileURLWithPath: argFilePath);
let argString=try! NSString(contentsOfURL: argFileUrl, encoding: NSUTF8StringEncoding);
let argLines=argString.description.characters.split("\n"); for l in argLines
{
let str=String(l);
let argWords=str.characters.split(",");
let host=String(argWords[]);
let username=String(argWords[]);
let password=String(argWords[]);
let path=String(argWords[]);
let passive=String(argWords[])=="True"; // upload
Upload(host,username: username,password: password,path: path,passive: passive);
} // delete temp argFile
try! NSFileManager.defaultManager().removeItemAtPath(argFilePath); NSRunLoop.mainRunLoop().run();
} Main();
main.swift
此 mac 工具是被 unity3d 的一键打包工具调用的,思路是将 shell 命令写在一个文件中,在 c# 中执行此 shell 文件以打开此工具。
shell 命令为,&1 为工具路径,是c#传过来的值:
#!/bin/bash
open $
调用上面 shell 文件的 c# 代码为:
if (!IsWindowSystem)
{
string rootPath = string.Format("{0}/Editor/BuildAssetBundle/Tools/", Application.dataPath.TrimEnd('/')); // save arguments to file
string tempFilePath = rootPath + "MacFtpUploader_Arguments";
File.WriteAllText(tempFilePath, sb.ToString()); // invoke tool
if (File.Exists(tempFilePath))
{
string toolPath = rootPath + "MacFtpUploader";
string shell = string.Format("{0}MacFtpUploaderInvoker.sh {1}", rootPath, toolPath);
Process.Start("/bin/bash", shell);
}
else
throw new InvalidOperationException(string.Format("Save arguments to file {0} failed, reupload again please...", tempFilePath));
}
运行结果为:
xcode 项目附件如下:
http://files.cnblogs.com/files/jietian331/MacFtpUploader.zip