SwiftUI项目中URL不支持问题求助
问题分析与修复方案
你的代码里存在两个核心问题导致URL无效:
1. URLComponents 未配置基础地址信息
你创建URLComponents时只设置了queryItems,但没有指定scheme(http)、host(127.0.0.1)、port(8000)和path(/home/),这会导致生成的URL是无效的空地址,自然无法请求后端。
2. 重复的手动编码操作
你先手动对userInputText做了addingPercentEncoding,但URLQueryItem会自动处理参数的URL编码,手动编码反而可能导致特殊字符重复转义,引发问题。
修正后的SwiftUI代码
import SwiftUI struct ContentView: View { @State private var userInputText = "" func submitTextData() { // 正确配置URLComponents的基础地址信息 var components = URLComponents() components.scheme = "http" components.host = "127.0.0.1" components.port = 8000 components.path = "/home/" // 直接传入原始文本,URLQueryItem会自动处理编码 components.queryItems = [URLQueryItem(name: "text", value: userInputText)] guard let url = components.url else { print("Failed to create valid URL") return } var request = URLRequest(url: url) request.httpMethod = "GET" URLSession.shared.dataTask(with: request) { data, response, error in if let error = error { print("Error submitting data:", error.localizedDescription) } else if let response = response as? HTTPURLResponse { print("Response status code:", response.statusCode) if response.statusCode == 200 { print("Text submitted successfully!") } else { print("Server returned error:", response.statusCode) } } }.resume() } var body: some View { VStack { TextField("Enter Text", text: $userInputText) .textFieldStyle(.roundedBorder) .padding() Button("Submit") { submitTextData() } .buttonStyle(.borderedProminent) } .padding() } }
额外注意事项
Django后端配置
确保你的Django项目中,urls.py配置了对应的路由:
# urls.py from django.urls import path from . import views urlpatterns = [ path('home/', views.home_view, name='home'), ]
然后在views.py中编写视图函数接收并打印参数:
# views.py from django.http import HttpResponse def home_view(request): if request.method == 'GET': text_input = request.GET.get('text', '') print("Received text from iOS:", text_input) return HttpResponse("Success", status=200)
iOS ATS 权限设置
由于你请求的是HTTP协议的本地地址,iOS默认会阻止这类请求。需要在项目的Info.plist中添加以下配置:
<key>NSAppTransportSecurity</key> <dict> <!-- 更安全的方式是只允许特定域名 --> <key>NSExceptionDomains</key> <dict> <key>127.0.0.1</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> <true/> </dict> </dict> </dict>
内容的提问来源于stack exchange,提问作者Ansh sharma
相关产品推荐
相关产品推荐

