我是iPhone应用开发的新手。我希望有一个异步方法,当我导航到应用程序中的各种视图时,将在成功登录时调用并工作异步。
此方法应独立工作,不会影响主视图方法。此方法正在执行本地文件夹上文件的ftp到服务器。
您能否告诉我或提供一些我可以参考的示例代码。我想看到ftp和异步方法进程。
答案 0 :(得分:1)
根据我的理解,你想从iphone上传一些东西到后台线程中的服务器? 无论如何;在后台线程下载应该非常相似。
首先,我建议您创建一个方法,为您完成主要工作:
- (void) createRessource {
NSURL *destinationDirURL = [NSURL URLWithString: completePathToTheFileYouWantToUpload];
CFWriteStreamRef writeStreamRef = CFWriteStreamCreateWithFTPURL(NULL, (__bridge CFURLRef) destinationDirURL);
ftpStream = (__bridge_transfer NSOutputStream *) writeStreamRef;
BOOL success = [ftpStream setProperty: yourFTPUser forKey: (id)kCFStreamPropertyFTPUserName];
if (success) {
NSLog(@"\tsuccessfully set the user name");
}
success = [ftpStream setProperty: passwdForYourFTPUser forKey: (id)kCFStreamPropertyFTPPassword];
if (success) {
NSLog(@"\tsuccessfully set the password");
}
ftpStream.delegate = self;
[ftpStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
// open stream
[ftpStream open];
}
此方法是作业的三分之一:它将在后台调用。 从这样的事情调用:
- (void) backgroundTask {
NSError *error;
done = FALSE;
/*
only 'prepares' the stream for upload
- doesn't actually upload anything until the runloop of this background thread is run!
*/
[self createRessource];
NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop];
do {
if(![currentRunLoop runMode: NSDefaultRunLoopMode beforeDate: [NSDate distantFuture]]) {
// log error if the runloop invocation failed
error = [[NSError alloc] initWithDomain: @"org.yourDomain.FTPUpload"
code: 23
userInfo: nil];
}
} while (!done && !error);
// close stream, remove from runloop
[ftpStream close];
[ftpStream removeFromRunLoop: [NSRunLoop currentRunLoop] forMode: NSDefaultRunLoopMode];
if (error) {
// handle error
}
/* if you want to upload more: put the above code in a lopp or upload the next ressource here or something like that */
}
现在你可以打电话了
[self performSelectorInBackground: @selector(backgroundTask) withObject: nil];
将为您创建一个后台线程,该流将在其runloop中进行调度,并配置并启动runloop。
最重要的是在后台线程中启动runloop - 如果没有它,流实现将永远不会开始工作......
主要从这里开始,我有类似的任务要执行: upload files in background via ftp on iphone