swift之向ftp服务器传文件
在 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服务器传文件的更多相关文章
- c#之向ftp服务器传文件
.Net提供了FtpWebRequest类,代码如下: using System; using System.Collections.Generic; using System.IO; using S ...
- FTP上传文件到服务器
一.初始化上传控件. 1.我们这里用dropzone.js作为上传控件,下载地址http://www.dropzonejs.com/ 2.这里我们使用一个div元素作为dropzone载体. < ...
- C# FTP上传文件至服务器代码
C# FTP上传文件至服务器代码 /// <summary> /// 上传文件 /// </summary> /// <param name="fileinfo ...
- C# FTP上传文件时出现"应 PASV 命令的请求,服务器返回了一个与 FTP 连接地址不同的地址。"的错误
FTP上传文件时出现"应 PASV 命令的请求,服务器返回了一个与 FTP 连接地址不同的地址."的错误 解决方法是在原代码上增加这句话 reqFTP.UsePassive = f ...
- PHP使用FTP上传文件到服务器(实战篇)
我们在做开发的过程中,上传文件肯定是避免不了的,平常我们的程序和上传的文件都在一个服务器上,我们也可以使用第三方sdk上传文件,但是文件在第三方服务器上.现在我们使用PHP的ftp功能把文件上传到我们 ...
- 再看ftp上传文件
前言 去年在项目中用到ftp上传文件,用FtpWebRequest和FtpWebResponse封装一个帮助类,这个在网上能找到很多,前台使用Uploadify控件,然后在服务器上搭建Ftp服务器,在 ...
- FTP上传文件提示550错误原因分析。
今天测试FTP上传文件功能,同样的代码从自己的Demo移到正式的代码中,不能实现功能,并报 Stream rs = ftp.GetRequestStream()提示远程服务器返回错误: (550) 文 ...
- FTP 上传文件
有时候需要通过FTP同步数据文件,除了比较稳定的IDE之外,我们程序员还可以根据实际的业务需求来开发具体的工具,具体的开发过程就不细说了,这里了解一下通过C#实现FTP上传文件到指定的地址. /// ...
- Java ftp 上传文件和下载文件
今天同事问我一个ftp 上传文件和下载文件功能应该怎么做,当时有点懵逼,毕竟我也是第一次,然后装了个逼,在网上找了一段代码发给同事,叫他调试一下.结果悲剧了,运行不通过.(装逼失败) 我找的文章链接: ...
随机推荐
- cisco 2950 3550 3750 系列交换机密码破解
破解密码原则:只删除密码 ,不破坏配置#本文中的#号表示注释的意思#第一步. 连接交换机的console口到终端#第二步. 按住交换机面板上的mode键的同时 插入电源,直到sys灯不闪,常亮再松开m ...
- MySQL的数据类型【总结】
1.时间类型 MySQL的DateTime,TimeStamp,Date和Time数据类型. DATETIME类型用在你需要同时包含日期和时间信息的值时.MySQL检索并且以'YYYY-MM-DD H ...
- 使用VS软件打开网站在浏览器浏览的方法
1.用VS软件打开网站之后,先检查网站是否使用IIS Express开发 2.若不是,则切换成使用IIS Express开发 3.检查项目使用的托管管道模式设置为经典模式了没有 4.最后选择“在浏览器 ...
- sql server统计字段的值在某些范围内中的个数
有一张表test如下: create table test ( id ,) primary key, num int ) 插入数据: ); ); ); ); ); ); ); ); ); ); ); ...
- python2.x 使用protobuf
1.在windows下配置protobuf 1.1 下载对应的包,包含两个:protoc.exe和源码文件(protoc也可以自己生成) 下载地址1 --- google code最近在迁移,也许以后 ...
- JQuery中$.ajax()方法参数详解 (20
url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数,请求方式(post或get)默认为get.注意其他http请求方法,例如put和 ...
- HttpServletResponse对象
Web服务器收到客户端的http请求,会针对每一次请求,分别创建一个用于代表请求的request对象.和代表响应的response对象. request和response对象即然代表请求和响应,那我们 ...
- AI 人工智能 探索 (三)
三类子弹的设计 using UnityEngine; using System.Collections; public class AI : AssembleModel { private Hasht ...
- ==和equals的异同
== 和 Equals 的区别 1. == 是一个运算符. 2.Equals则是string对象的方法,可以.(点)出来. 我们比较无非就是这两种 1.基本数据类型比较 2.引用对象比较 1.基本数据 ...
- Lucene入门教程
Lucene教程 1 lucene简介 1.1 什么是lucene Lucene是一个全文搜索框架,而不是应用产品.因此它并不像www.baidu.com 或者google Desktop那么 ...