iOS Swift使用Alamofire请求本地服务器报错-1002

707 阅读1分钟

出现场景

本地电脑搭建了一个服务器,想通过模拟器请求,使用是Alamofire框架。

let apiUrl = "localhost:8080/api"

Alamofire.request(apiUrl, method: .post, parameters: ["parameter" : "value"]).responseJSON { response in
    switch response.result.isSuccess {
    case true:
        print("Success!")
    case false:
        print(response.result.error!)
    }
}

运行时报以下错误

Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"
UserInfo={NSLocalizedDescription=unsupport URL,
NSErrorFailingURLStringKey=localhost:8080/api,
NSErrorFailingURLKey=localhost:8080/api,
_NSErrorRelatedURLSessionTaskErrorKey=("LocalDataTask <DF135230-13F1-221D-1123-2E33200EF21A>.<1>"),
_NSURLErrorFailingUrlSessionTaskErrorKey=LocalDataTask<DF135230-13F1-221D-1123-2E33200EF21A>.<1>,
NSUnderlyingError=0x6080000576d0 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}

解决方案

将url前面加上http或者https即可解决。

let apiUrl = "http://localhost:8080/api"