在 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

转载请注明出处:http://www.cnblogs.com/jietian331/p/5319357.html

swift之向ftp服务器传文件的更多相关文章

  1. c#之向ftp服务器传文件

    .Net提供了FtpWebRequest类,代码如下: using System; using System.Collections.Generic; using System.IO; using S ...

  2. FTP上传文件到服务器

    一.初始化上传控件. 1.我们这里用dropzone.js作为上传控件,下载地址http://www.dropzonejs.com/ 2.这里我们使用一个div元素作为dropzone载体. < ...

  3. C# FTP上传文件至服务器代码

    C# FTP上传文件至服务器代码 /// <summary> /// 上传文件 /// </summary> /// <param name="fileinfo ...

  4. C# FTP上传文件时出现"应 PASV 命令的请求,服务器返回了一个与 FTP 连接地址不同的地址。"的错误

    FTP上传文件时出现"应 PASV 命令的请求,服务器返回了一个与 FTP 连接地址不同的地址."的错误 解决方法是在原代码上增加这句话 reqFTP.UsePassive = f ...

  5. PHP使用FTP上传文件到服务器(实战篇)

    我们在做开发的过程中,上传文件肯定是避免不了的,平常我们的程序和上传的文件都在一个服务器上,我们也可以使用第三方sdk上传文件,但是文件在第三方服务器上.现在我们使用PHP的ftp功能把文件上传到我们 ...

  6. 再看ftp上传文件

    前言 去年在项目中用到ftp上传文件,用FtpWebRequest和FtpWebResponse封装一个帮助类,这个在网上能找到很多,前台使用Uploadify控件,然后在服务器上搭建Ftp服务器,在 ...

  7. FTP上传文件提示550错误原因分析。

    今天测试FTP上传文件功能,同样的代码从自己的Demo移到正式的代码中,不能实现功能,并报 Stream rs = ftp.GetRequestStream()提示远程服务器返回错误: (550) 文 ...

  8. FTP 上传文件

    有时候需要通过FTP同步数据文件,除了比较稳定的IDE之外,我们程序员还可以根据实际的业务需求来开发具体的工具,具体的开发过程就不细说了,这里了解一下通过C#实现FTP上传文件到指定的地址. /// ...

  9. Java ftp 上传文件和下载文件

    今天同事问我一个ftp 上传文件和下载文件功能应该怎么做,当时有点懵逼,毕竟我也是第一次,然后装了个逼,在网上找了一段代码发给同事,叫他调试一下.结果悲剧了,运行不通过.(装逼失败) 我找的文章链接: ...

随机推荐

  1. 【转】mysql函数

    MySQL函数 MySQL数据库提供了很多函数包括: 数学函数: 字符串函数: 日期和时间函数: 条件判断函数: 系统信息函数: 加密函数: 格式化函数: 一.数学函数 数学函数主要用于处理数字,包括 ...

  2. Service的启动方式

    Service的启动方式: 两种启动模式,一种是非绑定启动模式,另一种是绑定启动模式. 一.startservice方式启动 Intent intent = new Intent(this, Firs ...

  3. MySQL数据备份和恢复

    1.数据备份 mysqldump -uroot -p databasename > file.sql 2.数据还原 mysql -u root -p databasename < file ...

  4. 大varchar,test,blob数据类型的优化

    set global innodb-file-format=Barracuda 其它优化,后续补充

  5. 将undefault和null的数据转换成bool类型的数据 使用!!

    <script> var o={}; var a=null; console.info(!!o.name); </script> 输出false 此方法是将undefault和 ...

  6. 1.4 测试各阶段(单元、集成、系统 、Alpha、Beta、验收)

    单元测试:单元测试是对软件基本组成单元(软件设计的最小单位)进行正确性检验的测试工作,如函数.过程(function,procedure)或一个类的方法(method).单元测试是一个方法层面上的测试 ...

  7. Spring Boot 系列教程7-EasyUI-datagrid

    jQueryEasyUI jQuery EasyUI是一组基于jQuery的UI插件集合体,而jQuery EasyUI的目标就是帮助web开发者更轻松的打造出功能丰富并且美观的UI界面.开发者不需要 ...

  8. 文本格式ANSI,Unicode等有什么区别

    首先DBCS是亚洲的字符集,包含了ANSI,ANSI也就是ASCII值为0-255之间的字符,当字符为ANSI时,存放于文件中占用的是一个字节.如果是非ANSI的呢,则占用两字节.用VB的ASC函数可 ...

  9. 学习笔记——Windows7下Android与Cocos2dx的安装配置

    1.下载eclipse.安卓SDK.配置ADT等,android开发必备,略. 2.下载NDK.Cocos2dx.Cygwin 2.1NDK下载,请下载对应的32位或者64的较大的压缩包(较小的只有t ...

  10. 利用Hierarchy Viewer优化布局

    好久没更新博客了,趁着清明来写点什么. 今天来讲下如何使用android中提供的工具优化我们的布局.首先我们写一个最简单的框架布局. <?xml version="1.0" ...