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 上传文件和下载文件功能应该怎么做,当时有点懵逼,毕竟我也是第一次,然后装了个逼,在网上找了一段代码发给同事,叫他调试一下.结果悲剧了,运行不通过.(装逼失败) 我找的文章链接: ...
随机推荐
- 关于C++中虚函数表存放位置的思考
其实这是我前一段时间思考过的一个问题,是在看<深入探索C++对象模型>这本书的时候我产生的一个疑问,最近在网上又看到类似的帖子,贴出来看看: 我看到了很多有意思的答案,都回答的比较好,下面 ...
- android之DPAD上下左右四个键控制
我们代码的目的很简单,那就是监听上下左右中这几个键的事件触发.直接上代码: dpad.xml <?xml version="1.0" encoding="utf-8 ...
- 【二分图】 poj 1466
#include <iostream> #include <memory.h> #include <cstdio> using namespace std; int ...
- Hibernate 系列教程10-组成关系
组成关系 在一个员工模型里面需要存入 员工公司所在地址的城市,街道 员工籍贯所在的城市,街道, 此时可以抽取城市,街道变成一个模型即是组成关系 Employee public class Employ ...
- CodeForces 567B Berland National Library hdu-5477 A Sweet Journey
这类题一个操作增加多少,一个操作减少多少,求最少刚开始为多少,在中途不会出现负值,模拟一遍,用一个数记下最大的即可 #include<cstdio> #include<cstring ...
- shell注意事项
以下基于bash 1.shell只有变量和数组?,数组() 2.( (表达式1,表达式2…) ) 3.[ expr ] 实际上是bash 中 test 命令的简写.即所有的 [ expr ] 等于 t ...
- SqlMapClient ,SqlExecutor 和SqlMapClientTemplate 的区别?
SqlMapClient SqlExecutor SqlMapClientTemplate
- Office2003/2010等集成SP的简单方法
Office2003集成SP的简单方法 需要准备的工具:Office 2003 光盘镜像.SP3更新包.Office 2003 序列号.UltraISO,7-zip或winrar,虚拟光驱 步骤一:提 ...
- robot framework -记录错误
1.注意ie浏览器代理设置,报奇怪的错误 2.注意浏览器的安全设置,保护模式全部不要勾选
- 转:Selenium2.0之grid学习总结
(一)介绍: Grid的功能: 并行执行 通过一个中央管理器统一控制用例在不同环境.不同浏览器下运行 灵活添加变动测试机 (二)快速开始 这个例子将介绍如何使用selenium2.0的grid,并且注 ...