如何在Objective C中使用网络框架(在Swift中为示例)

问题描述 投票:0回答:1

[尝试通过具有“网络框架”(Swift)的IMAP协议与Google邮件服务器建立TCP连接,但出现错误。我从this(wwdc2018)视频中获得了代码。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    let connection = NWConnection(host: "imap.google.com", port: .imaps, using: .tls)

    let myQueue = DispatchQueue(label: "test")

    connection.stateUpdateHandler = { (newState) in
        switch (newState) {
        case .waiting(let error):
            print("ERROR - \(error)")
        case .preparing:
            print("I am HERE")
        case .ready:
            print("HELLO")
        case .failed(let error):
            print("ERROR + \(error)")
        default:
            break
        }
    }

    connection.start(queue: myQueue)

    return true
}

我的控制台显示:

我在这里

错误--65554:NoSuchRecord

UDPATED:感谢@arnt,我记得主机必须是“ imap.gmail.com”,现在可以正常使用!

主要目标是通过带有“网络框架”的IMAP协议与Google邮件服务器建立TCP连接,但在目标C上。

objective-c swift networking imap network-framework
1个回答
0
投票

我自己尝试过,成功了! =)

const char *hostname = "imap.gmail.com";
const char *port = "imaps";
nw_parameters_t parameters = nw_parameters_create_secure_tcp(NW_PARAMETERS_DEFAULT_CONFIGURATION, NW_PARAMETERS_DEFAULT_CONFIGURATION);
nw_endpoint_t endpoint = nw_endpoint_create_host(hostname, port);
nw_connection_t connection = nw_connection_create(endpoint, parameters);

nw_connection_set_queue(connection, dispatch_get_main_queue());
nw_connection_set_state_changed_handler(connection, ^(nw_connection_state_t state, nw_error_t error) {
    switch (state) {
        case nw_connection_state_waiting:
            NSLog(@"waiting");
            break;
        case nw_connection_state_failed:
            NSLog(@"failed");
            break;
        case nw_connection_state_ready:
            NSLog(@"connection is ready");
            break;
        case nw_connection_state_cancelled:
            NSLog(@"connection is cancelled");
            break;
        default:
            break;
    }
});
nw_connection_start(connection);
© www.soinside.com 2019 - 2024. All rights reserved.