Test FTP connection using CFReadStreamCreateWithFT

2019-09-13 01:34发布

I am using the following code to try to test an FTP connection:

func OpenAndTestFTPConn(user:NSString, pass:NSString) -> Bool {

    var ftpstring = "ftp://\(user):\(pass)@\(txtTarget.stringValue)"
    var ftpNSURL = NSURL(string: ftpstring)
    var FTPStream = CFReadStreamCreateWithFTPURL(nil, ftpNSURL)
    var status:Bool
    var cfstatus:Boolean = CFReadStreamOpen(FTPStream) as Boolean
    if cfstatus == 0 {
        status = false
    }
    else {
        status = true
    }
    println(status)
    return status

}

When I try building this, the line var cfstatus:Boolean = CFReadStreamOpen(FTPStream) as Boolean returns the error Cannot convert the expression's type 'Boolean' to type 'CFReadStream!'. If I remove the type declarations on both sides of the expression, the error returned is Cannot convert the expression's type 'Boolean' to type '$T3'.

Where am I going wrong?

Note: the cstatus definition and statements are based on this post.

1条回答
爷、活的狠高调
2楼-- · 2019-09-13 02:01

The CFReadStreamCreateWithFTPURL method returns an Unmanaged<CFReadStream> (per the docs), meaning that this particular function doesn't yet have Swift-compatible annotations indicating whether returned values have been retained or not. For more details, see "Unmanaged Objects" in this section of the Swift book.

For me, this code doesn't compile past the CFReadStreamCreateWithFTPURL call because of this issue. I don't see the Boolean error; it's strange that you're seeing that error and no error on the CFReadStreamCreateWithFTPURL call. Are you on Beta3?

I was able to get the code to compile with:

let FTPStream = CFReadStreamCreateWithFTPURL(nil, ftpNSURL).takeRetainedValue()

which converts the unmanaged value to an ARC-compatible pointer by asserting that the function has already retained the value (again, per its docs).

BTW, it's a nitpick, but all of your var's can be let's.

查看更多
登录 后发表回答