gpt4 book ai didi

ios - NSMutableURLRequest 和参数标签错误

转载 作者:行者123 更新时间:2023-11-28 15:37:25 24 4
gpt4 key购买 nike

我收到一条错误消息,提示“参数标签'(URL:, cachePolicy:, timeoutInterval:)' 不匹配任何可用的重载”,我不知道如何解决这个问题,有人知道吗?我正在使用 Swift 3.0 和 XCode 8.3.2 Here is my code

import Foundation
import UIKit
extension UIViewController {

func makeImageViewWithColor(_ color: UIColor) -> UIImage {
let rect: CGRect = CGRect (x: 0, y: 0, width: 1, height: 1)
color.setFill()
UIRectFill(rect)
let image:UIImage =UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
//Function Alert View
func alertView(title:String, message:String, alertStyle:UIAlertControllerStyle, alertAction:UIAlertAction) {
let alert:UIAlertController = UIAlertController(title: title, message: message, preferredStyle: alertStyle)
alert.addAction(alertAction)
self.present(alert, animated: true, completion: nil)
}


//Function query to server

func queryToServer(urlSource:String, postString:String, result:@escaping (_ dataResult:NSData?, _ errorResult:NSError) -> ()) {
let url:NSURL = NSURL(string: urlSource)!
let request = NSMutableURLRequest (URL: url, cachePolicy: NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10)
request.HTTPMethod = "POST"
request.HTTPBody = glGetString.dataUsingEncoding(NSUTF8StringEncoding)
let session = URLSession.shared
session.dataTaskWithRequest(request) { (data, response, error) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if error == nil {
result(dataResult: data, errorResult: nil)
} else {
result(dataResult: nil, errorResult: error)
}
})
}
}

}

最佳答案

根本不要在 Swift 3 中使用 NSMutableURLRequest

改用 Swift 3 原生语法,有新的结构 URLURLRequest

var 关键字使请求可变。

let url = URL(string: urlSource)!
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10)

PS:您的代码中的问题是大写的 URL 参数标签。


编辑:方法 queryToServer 的 Swift 3 等价物是:

func queryToServer(urlSource:String, postString:String, result:@escaping (Data?, Error?) -> ()) {
let url = URL(string: urlSource)!
var request = URLRequest (url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10)
request.httpMethod = "POST"
request.httpBody = postString.data(using: .utf8)
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
result(data, error)
}
}.resume()
}

调度 block 中的错误检查没有用。要么数据有效,要么错误为 nil,反之亦然。另一方面,您必须resume 数据任务才能启动它,glGetString 可能是 postString

关于ios - NSMutableURLRequest 和参数标签错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44157208/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com