Swift51.com
匿名 头像
匿名  2018-08-12 14:49

http數據獲取

回复:2  查看:4115  
func getDataFrom(UrlString : String) -> String?{
    let Url = URL (fileURLWithPath: UrlString)
    do{
        let _ = try Data(contentsOf: Url)
        return "success"
    }catch{
        print(error)
        return "fail"
    }
}

if let data = getDataFrom(UrlString: "http://www.baidu.com"){
    print(data)
}
報錯

Error Domain=NSCocoaErrorDomain Code=260 "The file “www.baidu.com” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/Users/xxx/Library/Developer/Xcode/DerivedData/DownloadWallpaper-fhscltsqxkthirfdumcybcadbkna/Build/Products/Debug/http:/www.baidu.com, NSUnderlyingError=0x100e072e0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

fail

Program ended with exit code: 0


Swift 头像
Swift  2018-08-13 20:07
看错误是找不到文件,可能是你代码URL传参数弄错了,let Url = URL (fileURLWithPath: UrlString), fileURLWithPath看名称就是个本地文件路径啊。