【问题标题】:How to use Network framework in Objective-C (example in Swift)如何在 Objective-C 中使用网络框架(Swift 中的示例)
【发布时间】:2020-04-17 17:09:21
【问题描述】:

尝试使用“网络框架”(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

已更新: 感谢@arnt,我记得主机必须是“imap.gmail.com”,现在可以正常工作了!

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

【问题讨论】:

  • 你得到 NoSuchRecord 因为 imap.google.com 不存在,它真的不存在,没有错误。您的意思可能是 imap.gmail.com,它确实存在。
  • @arnt,天哪,非常感谢!每次我在我的代码中都写对了,但我不知道为什么现在这样......

标签: objective-c swift networking imap network-framework


【解决方案1】:

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

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    • 2017-01-27
    • 1970-01-01
    相关资源
    最近更新 更多