iOS 修改userAgent --追加信息

本文介绍了解决iOS WebView不提供直接设置User-Agent接口时,如何通过在启动时获取原始User-Agent,然后在此基础上添加自定义信息的方法。通过这种方式,在请求时WebView的User-Agent将变为自定义设置的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原作者:http://blog.youkuaiyun.com/fangzhangsc2006/article/details/25840709


WebView 没有提供设置user-agent 的接口,无论是设置要加载的request,还是在delegate 中设置request,经测试都是无效的。如下:

方案一:

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];  
  2. [request addValue:@"Jiecao/2.4.7" forHTTPHeaderField:@"user-agent"];  
  3. [self.webView loadRequest:request];  
无效!!!


方案二:

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #pragma mark - webview delegate  
  2.   
  3. - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {  
  4.     NSMutableURLRequest *req = (NSMutableURLRequest *)request;  
  5.     [req addValue:@"Jiecao/2.4.7" forHTTPHeaderField:@"user-agent"];  
  6. }  

无效!!!


我的需求是不光要能更改user-agent,而且要保留WebView 原来的user-agent 信息,也就是说我需要在其上追加信息。在stackOverflow上搜集了多方答案,最终汇总的解决方案如下:

在启动时,比如在AppDelegate 中添加如下代码:

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. //get the original user-agent of webview  
  2. UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];  
  3. NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];  
  4. NSLog(@"old agent :%@", oldAgent);  
  5.   
  6. //add my info to the new agent  
  7. NSString *newAgent = [oldAgent stringByAppendingString:@" Jiecao/2.4.7 ch_appstore"];  
  8. NSLog(@"new agent :%@", newAgent);  
  9.   
  10. //regist the new agent  
  11. NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil nil];  
  12. [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];  

这样,WebView在请求时的user-agent 就是我们设置的这个了,如果需要在WebView 使用过程中再次变更user-agent,则需要再通过这种方式修改user-agent, 然后再重新实例化一个WebView。


参考:

http://stackoverflow.com/questions/478387/change-user-agent-in-uiwebview-iphone-sdk/23654363#23654363

<template> <div class="news-images"> <div v-for="(img, idx) in images" :key="idx" class="news-img-wrap"> <!-- 上传进度显示 --> <div v-if="img.status === 'uploading'" class="progress-overlay"> <van-circle v-model:current-rate="img.progress" :rate="100" :speed="10" size="120rem" :stroke-width="20" stroke-linecap="round" class="progress" > <span class="progress-text">{{ img.progress }}%</span> </van-circle> </div> <!-- 错误状态显示 --> <div v-if="img.status === 'error'" class="error-overlay"> <van-icon name="warning" size="32rem" color="#ff4444" /> <span>上传失败</span> <van-button type="primary" size="small" @click="reUpload(idx)" style="margin-top: 16rem">重新上传</van-button> </div> <img :src="img.url" class="news-img" /> <div class="img-close" @click="removeImg(idx)"> <van-icon name="cross" size="32rem" color="#fff" /> </div> </div> <div v-if="images.length < maxCount" class="news-img-add" @click="onAddImg"> <van-icon name="plus" size="64rem" color="#bbb" /> </div> <!-- 隐藏的文件选择器 --> <input ref="fileInput" type="file" multiple accept="image/*" style="display: none" @change="handleFileChange" /> </div> </template> <script setup lang="ts"> import { apis } from '@/api' import System from '@/utils/System' import { showToast } from 'vant' import { ref, onUnmounted } from 'vue' const emit = defineEmits(['update:modelValue']) const props = defineProps({ autoUpload: { type: Boolean, default: true }, maxCount: { type: Number, default: 9 }, modelValue: { type: Array as () => imgageItem[], default: () => [] } }) interface imgageItem { url: string progress: number status: 'pending' | 'uploading' | 'success' | 'error' file?: File } const fileInput = ref<HTMLInputElement | null>(null) const images = ref<imgageItem[]>(props.modelValue) const onAddImg = () => { fileInput.value?.click() } const removeImg = async (idx: number) => { images.value.splice(idx, 1) emit('update:modelValue', [...images.value]) } // const handleFileChange = async (e: Event) => { // const target = e.target as HTMLInputElement // const files = target.files // if (!files || files.length === 0) return // for (const file of Array.from(files)) { // if (images.value.length >= props.maxCount) break // try { // const reader = new FileReader() // console.log("🚀 ~ handleFileChange ~ reader:", reader) // reader.onload = (ev) => { // if (typeof ev.target?.result === 'string') { // const index = images.value.length // images.value.push({ // url: ev.target.result, // 临时预览URL // progress: 0, // status: 'pending', // file: file // }) // console.log("🚀 ~ handleFileChange ~ images.value:", images.value) // if (props.autoUpload) { // uploadFile(file, index) // } // reader.readAsDataURL(file) // } // } // // 清空 input // ;(e.target as HTMLInputElement).value = '' // // 更新父组件 // emit('update:modelValue', [...images.value]) // } catch (error) { // System.toast('图片处理失败') // console.error('文件处理错误:', error) // } // } // // 清空文件选择器 // ;(e.target as HTMLInputElement).value = '' // } const handleFileChange = (e: Event) => { const files = (e.target as HTMLInputElement).files if (files && files.length > 0) { Array.from(files).forEach((file) => { if (images.value.length >= 6) return const reader = new FileReader() reader.onload = (ev) => { if (typeof ev.target?.result === 'string') { const index = images.value.length images.value.push({ url: ev.target.result, // 临时预览URL progress: 0, status: 'pending', file: file }) // 开始上传 if (props.autoUpload) { uploadFile(file, index) } } } reader.readAsDataURL(file) }) emit('update:modelValue', [...images.value]) // 清空 input ;(e.target as HTMLInputElement).value = '' } } const uploadFile = async (file: File, index: number) => { // try { images.value[index].status = 'uploading' // 调用API上传 const formData = new FormData() formData.append("file",file) const res: any = await apis.uploadFile({ file: formData.get('file') }, (progressEvent: { loaded: number; total: number }) => { if (progressEvent.total > 0) { images.value[index].progress = Math.round((progressEvent.loaded / progressEvent.total) * 100) } }) if (res.code === 200) { images.value[index].status = 'success' images.value[index].url = res.data } else { images.value[index].status = 'error' System.toast('图片上传失败') } emit('update:modelValue', [...images.value]) // } catch (error) { // images.value[index].status = 'error' // System.toast('图片上传失败') // console.error('上传错误:', error) // emit('update:modelValue', [...images.value]) // } } // 自动上传全部待上传图片 const autoUploadAll = () => { images.value.forEach((img, index) => { if (img.status === 'pending' && img.file) { uploadFile(img.file, index) } }) } // 重新上传指定失败图片 const reUpload = (index: number) => { if (images.value[index].status !== 'error' || !images.value[index].file) return images.value[index].status = 'pending' uploadFile(images.value[index].file!, index) } // 组件卸载时清理临时文件 onUnmounted(async () => {}) defineExpose({ autoUploadAll, reUpload }) </script> <style lang="less" scoped> .news-images { display: flex; flex-wrap: wrap; gap: 18.5rem; margin-bottom: 48rem; .news-img-wrap { position: relative; width: 216rem; height: 216rem; border-radius: 23rem; overflow: hidden; margin-bottom: 32rem; // 新增,保证多行间距 .progress-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; z-index: 2; .progress { display: flex; align-items: center; justify-content: center; } .progress-text { color: #fff; font-size: 24rem; } } .error-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); display: flex; flex-direction: column; justify-content: center; align-items: center; z-index: 2; span { color: #fff; font-size: 24rem; margin-top: 8rem; } } .news-img { width: 100%; height: 100%; object-fit: cover; border-radius: 24rem; } .img-close { position: absolute; top: 8rem; right: 8rem; background: rgba(0, 0, 0, 0.4); border-radius: 50%; width: 40rem; height: 40rem; display: flex; align-items: center; justify-content: center; cursor: pointer; z-index: 3; } } .news-img-add { width: 216rem; height: 216rem; background: #f6f6f6; border-radius: 23rem; display: flex; align-items: center; justify-content: center; cursor: pointer; margin-bottom: 32rem; // 保持添加按钮与图片对齐 .van-icon { font-weight: bold; } } } </style> 这个代码帮我解决
最新发布
07-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值