2012-01-03 53 views
2

我是iPhone应用程序开发新手, 我想要一个异步方法,在我导航到应用程序中的各种视图时成功登录和异步工作时调用。 该方法应该独立工作,不会影响主视图方法。 此方法执行本地文件夹上的文件到服务器的ftp。 您能否告诉我或者提一些我可以参考的示例代码。 我想看到ftp和异步方法进程。 谢谢。在iPhone应用程序中使用异步方法调用的FTP文件

+0

请尽快回复其紧急我只需要知道正确的路径来实现此目的。 – Selwyn 2012-01-03 09:42:32

+0

可以请你打电话给我更多关于这个吗?,我不能得到你的观点 – maheswaran 2012-01-03 10:01:12

+0

其实我想实现一个方法,将做一个FTP在后台。这个过程不应该影响UI中的任何操作。如果你现在遵循我所需要的。请让我知道如果你仍然需要更多的了解我的问题。 – Selwyn 2012-01-03 10:49:19

回答

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